在Spring secuirty OAUTH中定义多个TokenStore

时间:2017-01-17 11:36:48

标签: java spring spring-security oauth-2.0 jwt

我有一个Spring Security AuthorizationServerConfigurerAdapter配置,它支持password和refresh_token授权类型。

clients
        .inMemory()
        .authorizedGrantTypes("password", "refresh_token")
        ...;

我正在使用的TokenStoreJwtTokenStore,因此我使用DefaultTokenServices

生成了refresh_token和access_token作为JWT

问题是如何在JdbcTokenStore生成和管理access_token的同时由JwtTokenStore生成和管理refresh_token?

我考虑过扩展DefaultTokenServices或实施AuthorizationServerTokenServices,但我不确定默认的spring-secuirty配置是否提供其他任何方式。

谢谢!

1 个答案:

答案 0 :(得分:3)

实现存储令牌(访问令牌和刷新令牌)并同时拥有JWT编码令牌的一种方法是提供tokenEnhancer类型为JwtAccessTokenConverter的令牌存储。

@Bean
protected TokenStore tokenStore() {
    return new InMemoryTokenStore();
}

@Bean
protected JwtAccessTokenConverter jwtTokenEnhancer() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    converter.setSigningKey(privateKey);
    converter.setVerifierKey(publicKey);
    return converter;
}

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.inMemory().withClient("client_trusted")//...
    ;
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints.tokenStore(tokenStore())
        .tokenEnhancer(jwtTokenEnhancer()) // <- tokens are encoded in JWT
        .authenticationManager(authenticationManager)
        .userDetailsService(userDetailsService);
    }

使用此方法,您可以轻松撤消(或删除)refresh_token。因此授权服务器不会在下次刷新令牌请求中提供新的访问令牌。并且JWT中的信息保持自包含,资源服务器可以在不与授权服务器交互的情况下工作。

@Autowired
protected TokenStore tokenStore;

@RequestMapping(method = RequestMethod.POST, value = "/revoke")
public void revokeToken(@RequestParam String token) {
    ((InMemoryTokenStore)tokenStore).removeRefreshToken(token);
}

以下是使用js client的授权和资源服务器的完整示例:https://github.com/pufface/spring-oauth-jwt-demo