Spring Cloud Security:Oauth2結合JWT使用

SpringBoot實戰電商項目mall(20k+star)地址: https://github.com/macrozheng/mall

摘要

Spring Cloud Security 爲構建安全的SpringBoot應用提供了一系列解決方案,結合Oauth2還能夠實現更多功能,好比使用JWT令牌存儲信息,刷新令牌功能,本文將對其結合JWT使用進行詳細介紹。java

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

建立oauth2-jwt-server模塊

該模塊只是對oauth2-server模塊的擴展,直接複製過來擴展下下便可。git

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);//配置令牌存儲策略
    }
    
    //省略代碼...
}
  • 運行項目後使用密碼模式來獲取令牌,訪問以下地址:http://localhost:9401/oauth/token

  • 進行獲取令牌操做,能夠發現令牌已經被存儲到Redis中。

使用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);
    }
    
    //省略代碼...
}
  • 運行項目後使用密碼模式來獲取令牌,訪問以下地址:http://localhost:9401/oauth/token

  • 發現獲取到的令牌已經變成了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();
    }

}
  • 將令牌放入Authorization頭中,訪問以下地址獲取信息:http://localhost:9401/user/getCurrentUser

刷新令牌

在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"); //添加受權模式
    }
}
  • 使用刷新令牌模式來獲取新的令牌,訪問以下地址:http://localhost:9401/oauth/token

使用到的模塊

springcloud-learning
└── oauth2-jwt-server -- 使用jwt的oauth2認證測試服務

項目源碼地址

https://github.com/macrozheng/springcloud-learninggithub

公衆號

mall項目全套學習教程連載中,關注公衆號第一時間獲取。web

公衆號圖片

相關文章
相關標籤/搜索