Spring Security从单体应用到分布式(五)-基于Zuul的Oauth2应用(二)

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值