代码地址

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

代码

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

  1. <dependency>
  2. <groupId>org.springframework.security</groupId>
  3. <artifactId>spring-security-jwt</artifactId>
  4. <version>1.0.9.RELEASE</version>
  5. </dependency>

添加配置文件JwtTokenStoreConfig.java

  1. @Configuration
  2. public class JwtTokenStoreConfig {
  3. @Bean
  4. public TokenStore jwtTokenStore(){
  5. return new JwtTokenStore(jwtAccessTokenConverter());
  6. }
  7. @Bean
  8. public JwtAccessTokenConverter jwtAccessTokenConverter(){
  9. JwtAccessTokenConverter accessTokenConverter = new
  10. JwtAccessTokenConverter();
  11. //配置JWT使用的秘钥
  12. accessTokenConverter.setSigningKey("123123");
  13. return accessTokenConverter;
  14. }
  15. }

在授权服务器配置中指定令牌的存储策略为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请求
}

image.png

测试

获取token

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

发现已经是jwt token了
image.png

测试访问指定微服务

也能访问通过

image.png

解析token

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