Spring Cloud Security:Oauth2結合JWT使用

MacroZheng發表於2019-11-06

SpringBoot實戰電商專案mall(20k+star)地址:github.com/macrozheng/…

摘要

Spring Cloud Security 為構建安全的SpringBoot應用提供了一系列解決方案,結合Oauth2還可以實現更多功能,比如使用JWT令牌儲存資訊,重新整理令牌功能,本文將對其結合JWT使用進行詳細介紹。

JWT簡介

JWT是JSON WEB TOKEN的縮寫,它是基於 RFC 7519 標準定義的一種可以安全傳輸的的JSON物件,由於使用了數字簽名,所以是可信任和安全的。

JWT的組成

  • JWT token的格式:header.payload.signature;
  • header中用於存放簽名的生成演算法;
{
  "alg": "HS256",
  "typ": "JWT"
}
複製程式碼
  • payload中用於存放資料,比如過期時間、使用者名稱、使用者所擁有的許可權等;
{
  "exp": 1572682831,
  "user_name": "macro",
  "authorities": [
    "admin"
  ],
  "jti": "c1a0645a-28b5-4468-b4c7-9623131853af",
  "client_id": "admin",
  "scope": [
    "all"
  ]
}
複製程式碼
  • signature為以header和payload生成的簽名,一旦header和payload被篡改,驗證將失敗。

JWT例項

  • 這是一個JWT的字串:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NzI2ODI4MzEsInVzZXJfbmFtZSI6Im1hY3JvIiwiYXV0aG9yaXRpZXMiOlsiYWRtaW4iXSwianRpIjoiYzFhMDY0NWEtMjhiNS00NDY4LWI0YzctOTYyMzEzMTg1M2FmIiwiY2xpZW50X2lkIjoiYWRtaW4iLCJzY29wZSI6WyJhbGwiXX0.x4i6sRN49R6JSjd5hd1Fr2DdEMBsYdC4KB6Uw1huXPg
複製程式碼
  • 可以在該網站上獲得解析結果:jwt.io/

Spring Cloud Security:Oauth2結合JWT使用

建立oauth2-jwt-server模組

該模組只是對oauth2-server模組的擴充套件,直接複製過來擴充套件下下即可。

oauth2中儲存令牌的方式

在上一節中我們都是把令牌儲存在記憶體中的,這樣如果部署多個服務,就會導致無法使用令牌的問題。 Spring Cloud Security中有兩種儲存令牌的方式可用於解決該問題,一種是使用Redis來儲存,另一種是使用JWT來儲存。

使用Redis儲存令牌

  • 在pom.xml中新增Redis相關依賴:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
複製程式碼
  • 在application.yml中新增redis相關配置:
spring:
  redis: #redis相關配置
    password: 123456 #有密碼時設定
複製程式碼
  • 新增在Redis中儲存令牌的配置:
/**
 * 使用redis儲存token的配置
 * Created by macro on 2019/10/8.
 */
@Configuration
public class RedisTokenStoreConfig {

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    @Bean
    public TokenStore redisTokenStore (){
        return new RedisTokenStore(redisConnectionFactory);
    }
}
複製程式碼
  • 在認證伺服器配置中指定令牌的儲存策略為Redis:
/**
 * 認證伺服器配置
 * Created by macro on 2019/9/30.
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserService userService;

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

    /**
     * 使用密碼模式需要配置
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(userService)
                .tokenStore(tokenStore);//配置令牌儲存策略
    }
    
    //省略程式碼...
}
複製程式碼

Spring Cloud Security:Oauth2結合JWT使用

  • 進行獲取令牌操作,可以發現令牌已經被儲存到Redis中。

Spring Cloud Security:Oauth2結合JWT使用

使用JWT儲存令牌

  • 新增使用JWT儲存令牌的配置:
/**
 * 使用Jwt儲存token的配置
 * Created by macro on 2019/10/8.
 */
@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;
    }
}
複製程式碼
  • 在認證伺服器配置中指定令牌的儲存策略為JWT:
/**
 * 認證伺服器配置
 * Created by macro on 2019/9/30.
 */
@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);
    }
    
    //省略程式碼...
}
複製程式碼

Spring Cloud Security:Oauth2結合JWT使用

  • 發現獲取到的令牌已經變成了JWT令牌,將access_token拿到https://jwt.io/ 網站上去解析下可以獲得其中內容。
{
  "exp": 1572682831,
  "user_name": "macro",
  "authorities": [
    "admin"
  ],
  "jti": "c1a0645a-28b5-4468-b4c7-9623131853af",
  "client_id": "admin",
  "scope": [
    "all"
  ]
}
複製程式碼

擴充套件JWT中儲存的內容

有時候我們需要擴充套件JWT中儲存的內容,這裡我們在JWT中擴充套件一個key為enhance,value為enhance info的資料。

  • 繼承TokenEnhancer實現一個JWT內容增強器:
/**
 * Jwt內容增強器
 * Created by macro on 2019/10/8.
 */
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例項:
/**
 * 使用Jwt儲存token的配置
 * Created by macro on 2019/10/8.
 */
@Configuration
public class JwtTokenStoreConfig {
    
    //省略程式碼...

    @Bean
    public JwtTokenEnhancer jwtTokenEnhancer() {
        return new JwtTokenEnhancer();
    }
}
複製程式碼
  • 在認證伺服器配置中配置JWT的內容增強器:
/**
 * 認證伺服器配置
 * Created by macro on 2019/9/30.
 */
@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);
    }

    //省略程式碼...
}
複製程式碼
  • 執行專案後使用密碼模式來獲取令牌,之後對令牌進行解析,發現已經包含擴充套件的內容。
{
  "user_name": "macro",
  "scope": [
    "all"
  ],
  "exp": 1572683821,
  "authorities": [
    "admin"
  ],
  "jti": "1ed1b0d8-f4ea-45a7-8375-211001a51a9e",
  "client_id": "admin",
  "enhance": "enhance info"
}
複製程式碼

Java中解析JWT中的內容

如果我們需要獲取JWT中的資訊,可以使用一個叫jjwt的工具包。

  • 在pom.xml中新增相關依賴:
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.9.0</version>
</dependency>
複製程式碼
  • 修改UserController類,使用jjwt工具類來解析Authorization頭中儲存的JWT內容。
/**
 * Created by macro on 2019/9/30.
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @GetMapping("/getCurrentUser")
    public Object getCurrentUser(Authentication authentication, HttpServletRequest request) {
        String header = request.getHeader("Authorization");
        String token = StrUtil.subAfter(header, "bearer ", false);
        return Jwts.parser()
                .setSigningKey("test_key".getBytes(StandardCharsets.UTF_8))
                .parseClaimsJws(token)
                .getBody();
    }

}
複製程式碼

Spring Cloud Security:Oauth2結合JWT使用

重新整理令牌

在Spring Cloud Security 中使用oauth2時,如果令牌失效了,可以使用重新整理令牌通過refresh_token的授權模式再次獲取access_token。

  • 只需修改認證伺服器的配置,新增refresh_token的授權模式即可。
/**
 * 認證伺服器配置
 * Created by macro on 2019/9/30.
 */
@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"); //新增授權模式
    }
}
複製程式碼

Spring Cloud Security:Oauth2結合JWT使用

使用到的模組

springcloud-learning
└── oauth2-jwt-server -- 使用jwt的oauth2認證測試服務
複製程式碼

專案原始碼地址

github.com/macrozheng/…

公眾號

mall專案全套學習教程連載中,關注公眾號第一時間獲取。

公眾號圖片

相關文章