Oauth2结合JWT使用
前言
Spring Cloud Security 为构建安全的SpringBoot应用提供了一系列解决方案,结合Oauth2还可以实现更多功能,比如使用JWT令牌存储信息,刷新令牌功能。
一、JWT
JWT token的格式:header.payload.signature;header中用于存放签名的生成算法,我们最常用的就是HS256;payload中用于存放数据,比如过期时间、用户名、用户所拥有的权限等;signature为以header和payload生成的签名,一旦header和payload被篡改,验证将失败,签名生效最主要的因素是因为签名中加salt,这种情况下保证了签名可以不被破解。
我们可以利用https://jwt.io/
进行编解码,这个工具十分好用,建议初学者网上找一个Jwt实例,然后去进行编解码。
二、使用步骤
我们存储令牌的两种方式,一种是运用Redis去存储令牌,这个我们不在去详述,今天我们主要讲解使用JWT去存储令牌。
1.添加使用JWT存储令牌的配置
@Configuration
public class JwtTokenStoreConfig {
@Bean
public TokenStore jwtTokenStore() {
return new JwtTokenStore(jwtAccessTokenConverter());
}
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter();
accessTokenConverter.setSigningKey("test_key");//配置JWT使用的秘钥
return accessTokenConverter;
}
}
2 .在认证服务器配置中指定令牌的存储策略为JWT
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserService userService;
@Autowired
@Qualifier("jwtTokenStore")
private TokenStore tokenStore;
@Autowired
private JwtAccessTokenConverter jwtAccessTokenConverter;
@Autowired
private JwtTokenEnhancer jwtTokenEnhancer;
/**
* 使用密码模式需要配置
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.authenticationManager(authenticationManager)
.userDetailsService(userService)
.tokenStore(tokenStore) //配置令牌存储策略
.accessTokenConverter(jwtAccessTokenConverter);
}
//省略代码...
}
运行项目后使用密码模式来获取令牌,访问如下地址:http://localhost:9401/oauth/token.
发现获取到的令牌已经变成了JWT令牌,将access_token拿到https://jwt.io/ 网站上去解析下可以获得其中内容。
有时候我们需要扩展JWT中存储的内容,这里我们在JWT中扩展一个key为enhance,value为enhance info的数据。
1.继承TokenEnhancer实现一个JWT内容增强器
public class JwtTokenEnhancer implements TokenEnhancer {
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
Map<String, Object> info = new HashMap<>();
info.put("enhance", "enhance info");
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(info);
return accessToken;
}
}
//返回一个JwtTokenEnhancer实例,我们可以去操作这个实例
@Configuration
public class JwtTokenStoreConfig {
//省略代码...
@Bean
public JwtTokenEnhancer jwtTokenEnhancer() {
return new JwtTokenEnhancer();
}
}
2 .在认证服务中配置相应内容增强器功能
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserService userService;
@Autowired
@Qualifier("jwtTokenStore")
private TokenStore tokenStore;
@Autowired
private JwtAccessTokenConverter jwtAccessTokenConverter;
@Autowired
private JwtTokenEnhancer jwtTokenEnhancer;
/**
* 使用密码模式需要配置
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
List<TokenEnhancer> delegates = new ArrayList<>();
delegates.add(jwtTokenEnhancer); //配置JWT的内容增强器
delegates.add(jwtAccessTokenConverter);
enhancerChain.setTokenEnhancers(delegates);
endpoints.authenticationManager(authenticationManager)
.userDetailsService(userService)
.tokenStore(tokenStore) //配置令牌存储策略
.accessTokenConverter(jwtAccessTokenConverter)
.tokenEnhancer(enhancerChain);
}
//省略代码...
}
后面的流程就和上面的流程是一样的,再返回的token中,我们解码一下,应该可以发现会多了一个key-value的增强数据结构。
三、刷新令牌
在Spring Cloud Security 中使用oauth2时,如果令牌失效了,可以使用刷新令牌通过refresh_token的授权模式再次获取access_token。只需修改认证服务器的配置,添加refresh_token的授权模式即可。
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("admin")
.secret(passwordEncoder.encode("admin123456"))
.accessTokenValiditySeconds(3600)
.refreshTokenValiditySeconds(864000)
.redirectUris("http://www.baidu.com")
.autoApprove(true) //自动授权配置
.scopes("all")
.authorizedGrantTypes("authorization_code","password","refresh_token"); //添加授权模式
}
}
使用刷新令牌模式来获取新的令牌,访问如下地址:http://localhost:9401/oauth/token,我们发现token已经刷新。
总结
在这个模块,我们使用了 oauth2-jwt-server ,这个模块提供了使用jwt的oauth2认证测试服务,在我们使用token来进行验证时,token是存在客户端的,这个和我们之前的验证的sessionID存在服务端还是有区别的,在数据量特别庞大的情况下,我们使用token存储信息,能够极大地减轻服务端的存储压力。这就是token的好处,目前我们使用JWT存储token,当然是一种较好的思路,但是我们要考虑到作为分布式服务,这种JWT是不方便共享的,如果我们要实现共享,当然是使用分布式缓存去Redis去存储token,这种情况下我们就可以共享。