Spring Secuirty Oauth2将token换成jwt

代码地址

https://gitee.com/zjj19941/ZJJ_Neaten5.10/tree/master/ZJJ_SpringCloud_Oauth2/demo04

代码

在之前的spring security Oauth2的代码基础上修改
引入依赖

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-jwt</artifactId>
    <version>1.0.9.RELEASE</version>
</dependency>

添加配置文件JwtTokenStoreConfig.java

@Configuration
public class JwtTokenStoreConfig {
 
    @Bean
    public TokenStore jwtTokenStore(){
        return new JwtTokenStore(jwtAccessTokenConverter());
    }
 
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter(){
        JwtAccessTokenConverter accessTokenConverter = new
                JwtAccessTokenConverter();
        //配置JWT使用的秘钥
        accessTokenConverter.setSigningKey("123123");
        return accessTokenConverter;
    }
}

在授权服务器配置中指定令牌的存储策略为JWT

@Autowired
@Qualifier("jwtTokenStore")
private TokenStore tokenStore;

@Autowired
private JwtAccessTokenConverter jwtAccessTokenConverter;


@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

    endpoints.authenticationManager(authenticationManagerBean) //使用密码模式需要配置
        .tokenStore(tokenStore)  //配置存储令牌策略
        .accessTokenConverter(jwtAccessTokenConverter)
        .reuseRefreshTokens(false)  //refresh_token是否重复使用
        .userDetailsService(userService) //刷新令牌授权包含对用户信息的检查
        .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST); //支持GET,POST请求
}

Spring Secuirty Oauth2将token换成jwt

测试

获取token

http://localhost:8080/oauth/token?username=fox&password=123456&grant_type=password&client_id=client&client_secret=123123&scope=all

发现已经是jwt token了
Spring Secuirty Oauth2将token换成jwt

测试访问指定微服务

也能访问通过

Spring Secuirty Oauth2将token换成jwt

解析token

将access_token拿到https://jwt.io/ 网站上去解析下可以获得其中内容。
或者是在https://www.box3.cn/tools/jwt.html去解析
Spring Secuirty Oauth2将token换成jwt

上一篇:HGAME-week1


下一篇:26 drf-jwt修改签发响应格式