我们这里要实现的是替换原来的token方式使用jwt进行token的分发和验证;
这里依然使用密码模式进行示范
整体流程:
- 在验证模式(测试的密码模式),中使用.tokenStore()配置toekn管理;
- 这里传入的必须是我们自己重新配置的jwttokenstore
- 创建配置类
JwtTokenConfig
创建beanJwtTokenStore
和JwtAccessTokenConverter
返回(这里配置盐
),同时在类中需要将JwtAccessTokenConverter()
传入给JwtTokenStore
- 在1的配置中将
JwtTokenStore
传入给tokenStore
,将JwtAccessTokenConverter
传入给.accessTokenConverter()
代码:
tokenStore配置类:
/**
* jwttoken配置类
* @author guochao
*/
@Configuration
public class JwtTokenConfig {
@Value("${yan}")
private String yan;
//将下面配置的转换器bean注入
@Autowired
private JwtAccessTokenConverter jwtAccessTokenConverter;
//整体流程:利用一个转换器将默认token转换为jwtToken
@Bean
public TokenStore jwtTokenStore(){
//创建一个JwtTokenStore,传入token转换器并返回,注意这里创建的是jwt
return new JwtTokenStore(jwtAccessTokenConverter());
}
//jwt创建转换器
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter(){
JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
//设置盐
jwtAccessTokenConverter.setSigningKey(yan);
return jwtAccessTokenConverter;
}
}
配置验证;
@Autowired
@Qualifier("jwtTokenStore")
private TokenStore jwtTokenStore;
/**
* 密码模式配置
* @param endpoints
* @throws Exception
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
//自定义登录逻辑,我们把之前自定义的登录逻辑类注进来填进去(实现UserDetailService的类)
.userDetailsService(userDetailsService)
//配置授权管理器
.authenticationManager(authenticationManager)
//redis保存tokenStore模式
//.tokenStore(tokenStore);
//使用jwt实现token,注入我们定义的jwtTokenStore
.tokenStore(jwtTokenStore)
//配置转换器
.accessTokenConverter(jwtAccessTokenConverter);
}
【这里目前存在一个spring使用boot版本oauth2的bug,稍后修复。先搬砖】
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Greenwich.SR1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
原来使用的是springboot的security和oauth2,现在改成使用springcloud的,以修复bug;注意springbooot版本的对应
自定义security-jwt 载荷