前言
在前面的笔记分享中,我们知道了OAuth 2是什么,他是一个第三方登录的授权协议。为什么要使用 OAuth 2,因为现在是分布式架构,对客户来说,是一个系统,但是后台实现是多个微服务,客户一次登录,应该要能访问到不同的微服务。今天我们接着学习 OAuth2 的实战。
工程结构;
授权服务器:颁发和验证令牌
提供需要令牌才能访问的服务
依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
</dependency>
授权服务器配置
oauth2 配置类继承
AuthorizationServerConfigurerAdapter
开启授权服务器
@EnableAuthorizationServer
客户端信息配置
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.inMemory()
.withClient(CLIENT_ID)
.secret(SECRET_CHAR_SEQUENCE)
.autoApprove(false)
.redirectUris("http://127.0.0.1:8084/cms/login") //重定向uri
.scopes(ALL)
.accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS)
.authorizedGrantTypes(AUTHORIZATION_CODE, IMPLICIT, GRANT_TYPE_PASSWORD, CLIENT_CREDENTIALS);
}
存储令牌
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager).tokenStore(memoryTokenStore());
}
@Bean
public TokenStore memoryTokenStore() {
return new InMemoryTokenStore();
}
oauth2端点权限
/**
* 认证服务器的安全配置
*
* @param security
* @throws Exception
*/
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security
// 开启/oauth/check_token验证端口认证权限访问,checkTokenAccess("isAuthenticated()")设置授权访问
.checkTokenAccess("permitAll()")
//允许表单认证
.allowFormAuthenticationForClients();
}
SecurityConfig配置类 继承
WebSecurityConfigurerAdapter
开启Spring Security
@EnableWebSecurity
设置用户角色数据内存存储
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception { //auth.inMemoryAuthentication()
auth.inMemoryAuthentication()
.withUser("lxs")
.password("{noop}123") //使用springsecurity5,需要加上{noop}指定使用NoOpPasswordEncoder给DelegatingPasswordEncoder去校验密码
.roles("admin");
}
放行静态资源
@Override
public void configure(WebSecurity web) throws Exception {
//解决静态资源被拦截的问题
// web.ignoring().antMatchers("/asserts/**");
}
授权资源全局配置
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin().permitAll()
.and().logout().logoutUrl("/logout").logoutSuccessUrl("/")
.and().authorizeRequests().antMatchers("/oauth/**", "/login/**", "/logout/**", "/api/**").permitAll()
.anyRequest().authenticated()
// 关闭跨域保护;
.and().csrf().disable();
}
资源服务器配置
Oauth2配置类继承
ResourceServerConfigurerAdapter
@Configuration
@EnableResourceServer
public class Oauth2ResourceServerConfiguration extends
ResourceServerConfigurerAdapter {
private static final String CHECK_TOKEN_URL = "http://localhost:8888/oauth/check_token";
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
RemoteTokenServices tokenService = new RemoteTokenServices();
// 授权服务器令牌校验地址
tokenService.setCheckTokenEndpointUrl(CHECK_TOKEN_URL);
// 客户端信息
tokenService.setClientId("cms");
tokenService.setClientSecret("secret");
resources.tokenServices(tokenService);
}
}
Security配置类继承
WebSecurityConfigurerAdapter
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// 授权拦截路径
http.authorizeRequests().antMatchers("/**").authenticated();
// 禁用CSRF,关闭跨域保护
http.csrf().disable();
}
}