最近的项目中需要实现Oauth2,因为spring security本身已经有了这样的功能,只要集成进来就可以开箱即用,所以选择了已有的框架。由于是第一次使用框架,在使用的过程中,整体的感觉就是比较重,项目启动也有变慢,而且配置复杂,对新手并不是很友好。
集成security要进行的主要配置有三个:
- 对authServer的配置
以下示例代码是通过redis进行token的存储,通过mysql进行授权信息的管理。spring security中自带了一套mysql的表,在官方网站可以获得。
@Configuration
@EnableAuthorizationServer
public class AuthServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
private OauthClientDetailsServiceImpl oauthClientDetailsService;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserDetailServiceImpl userDetailService;
@Autowired
private DruidDataSource dataSource;
@Autowired
private JedisConnectionFactory jedisConnectionFactory;
@Bean
public ApprovalStore approvalStore() {
return new JdbcApprovalStore(dataSource);
}
/**
* access_token 采用redis缓存
* @return
*/
@Bean
public RedisTokenStore tokenStore() {
return new RedisTokenStore(jedisConnectionFactory);
}
/**
* 授权码的存储
* @return
*/
@Bean
public AuthorizationCodeServices authorizationCodeServices() {
JdbcAuthorizationCodeServices service = new JdbcAuthorizationCodeServices(dataSource);
return service;
}
// 配置服务客户端
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.withClientDetails(oauthClientDetailsService);
}
/**
* 配置oauth2端点信息
* @param endpoints
* @throws Exception
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
.authenticationManager(authenticationManager)
.approvalStore(approvalStore())
.userDetailsService(userDetailService)
.tokenStore(tokenStore())
.authorizationCodeServices(authorizationCodeServices());
// 自定义确认授权页面
endpoints.pathMapping("/oauth/confirm_access", "/oauth/confirm_access");
// 自定义错误页
endpoints.pathMapping("/oauth/error", "/oauth/error");
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.checkTokenAccess("isAuthenticated()").tokenKeyAccess("permitAll()")
.allowFormAuthenticationForClients();
}
}
若通过内存进行
- 对resourceServer的配置
- 对spring security框架的配置