1.问题
在上篇博文Spring Security从单体应用到分布式(四)-基于Zuul的Oauth2应用中因为在token存储仅仅使用了InMemoryTokenStore内存作为存储,因此申请到的accessToken也只能在这个服务中使用。Spring Security提供了JDBC,Reids等存储方式,考虑到登录功能是一个访问频繁而且需要快速响应的功能,因此这次将使用Redis实现多服务统一鉴权。
2.请求流向图
3.配置
追加redis的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
4.代码修改
鉴权服务作为入口需要替换原来的的InMemoryTokenStore
public class OAuth2ServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private RedisTemplate redisTemplate;
@Bean
public RedisTokenStore redisTokenStore()
{
return new RedisTokenStore(redisTemplate.getConnectionFactory());
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(customAuthenticationManager());
endpoints.allowedTokenEndpointRequestMethods(HttpMethod.GET,HttpMethod.POST);
endpoints.tokenStore(redisTokenStore());
}
}
所有提供资源api的服务系统需要追加资源服务的配置,并且使用RedisTokenStore作为存取媒介,配合网关的鉴权拦截添加/api/**。
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Autowired
private RedisTemplate redisTemplate;
@Override
public void configure(HttpSecurity http) throws Exception {
http.antMatcher("/api/**").authorizeRequests().anyRequest().authenticated();
}
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore(new RedisTokenStore(redisTemplate.getConnectionFactory()));
resources.resourceId("resourece").tokenServices(defaultTokenServices);
}
}
因为引入了Reids作为存储媒介,服务中对应用户信息的存储就需要序列和反序列化,因此要把使用到的对象提到一个服务中,并且用上Serializable接口
public class CustomUser implements UserDetails, Serializable {
}
5.效果
github:https://github.com/tale2009/spring-security-learning/tree/master/cloudsecurityplus