为什么使用jwt?
在原先dubbo+zookeeper项目中,web模块只暴露Restful接口,各服务模块只暴露duboo接口,此时用户登录后由web项目进行token的鉴权和验证,并通过dubbo的隐式传参将sessionID传递给dubbo服务模块, 拦截器再根据sessionID从Redis中获取用户信息设置到当前线程
然鹅,在springcloud中,各个微服务直接暴露的是restful接口,此时如何让各个微服务获取到当前用户信息呢?最佳的方式就是token了,token作为BS之间的会话标识(一般是原生随机token),同时也可以作为信息的载体传递一些自定义信息(jwt, 即Json web token)。
为了能更清楚的了解本文,需要对spring-security-oauth 及 jwt有一定了解,本文只关注用户信息传递这一块
认证服务器
认证服务器配置AuthorizationServerConfigurerAdapter
@Configuration
@PropertySource({"classpath:application.yml"})
@EnableAuthorizationServer
public class AuthServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
AuthenticationManager authenticationManager;
@Autowired
TokenStore tokenStore;
@Autowired
JwtAccessTokenConverter jwtAccessTokenConverter;
@Autowired
ApprovalStore approvalStore;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.jdbc(dataSource());
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager)
.tokenStore(tokenStore)
.accessTokenConverter(jwtAccessTokenConverter)
.approvalStore(approvalStore)
.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
//允许表单认证
security
.tokenKeyAccess("permitAll()") //url:/oauth/token_key,exposes public key for token verification if using JWT tokens
.checkTokenAccess("permitAll()")
.allowFormAuthenticationForClients();
}
@Bean
@Primary
@ConfigurationProperties("ms-sql.datasource")
public DataSource dataSource() {
return new DriverManagerDataSource();
}
@Bean
public ApprovalStore approvalStore() {
return new JdbcApprovalStore(dataSource());
}
/**
* 使用 Jwt token
* @param accessTokenConverter
* @return
*/
@Bean
public TokenStore tokenStore(@Autowired JwtAccessTokenConverter accessTokenConverter) {
return new JwtTokenStore(accessTokenConverter);
}
/**
* token 转换器,加入对称秘钥,使用自