Spring Cloud入門-Oauth2授權之JWT集成(Hoxton版本)

項目使用的Spring Cloud爲Hoxton版本,Spring Boot爲2.2.2.RELEASE版本

Spring Cloud入門系列彙總

序號 內容 鏈接地址
1 Spring Cloud入門-十分鐘瞭解Spring Cloud https://blog.csdn.net/ThinkWon/article/details/103715146
2 Spring Cloud入門-Eureka服務註冊與發現(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103726655
3 Spring Cloud入門-Ribbon服務消費者(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103729080
4 Spring Cloud入門-Hystrix斷路器(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103732497
5 Spring Cloud入門-Hystrix Dashboard與Turbine斷路器監控(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103734664
6 Spring Cloud入門-OpenFeign服務消費者(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103735751
7 Spring Cloud入門-Zuul服務網關(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103738851
8 Spring Cloud入門-Config分佈式配置中心(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103739628
9 Spring Cloud入門-Bus消息總線(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103753372
10 Spring Cloud入門-Sleuth服務鏈路跟蹤(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103753896
11 Spring Cloud入門-Consul服務註冊發現與配置中心(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103756139
12 Spring Cloud入門-Gateway服務網關(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103757927
13 Spring Cloud入門-Admin服務監控中心(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103758697
14 Spring Cloud入門-Oauth2授權的使用(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103761687
15 Spring Cloud入門-Oauth2授權之JWT集成(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103763364
16 Spring Cloud入門-Oauth2授權之基於JWT完成單點登錄(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103766368
17 Spring Cloud入門-Nacos實現註冊和配置中心(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103769680
18 Spring Cloud入門-Sentinel實現服務限流、熔斷與降級(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103770879
19 Spring Cloud入門-Seata處理分佈式事務問題(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103786102
20 Spring Cloud入門-彙總篇(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103786588

摘要

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中用於存放數據,比如過期時間、用戶名、用戶所擁有的權限等;

{
  "user_name": "jourwon",
  "scope": [
    "all"
  ],
  "exp": 1577678449,
  "authorities": [
    "admin"
  ],
  "jti": "618cda6a-dfce-4966-b0df-00607f693ab5",
  "client_id": "admin"
}

signature爲以header和payload生成的簽名,一旦header和payload被篡改,驗證將失敗。

JWT實例

這是一個JWT的字符串:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJqb3Vyd29uIiwic2NvcGUiOlsiYWxsIl0sImV4cCI6MTU3NzY3Nzc2MywiYXV0aG9yaXRpZXMiOlsiYWRtaW4iXSwianRpIjoiMGY4NmE2ODUtZDIzMS00M2E0LWJhZjYtNzAwMmE0Yzg1YmM1IiwiY2xpZW50X2lkIjoiYWRtaW4iLCJlbmhhbmNlIjoiZW5oYW5jZSBpbmZvIn0.RLrkBQEOdCikiz0SsJ8ZsVcxk8GkAyKsOj5fZytgNF8

可以在該網站上獲得解析結果:https://jwt.io/

在這裏插入圖片描述

創建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>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-security</artifactId>
</dependency>

在application.yml中添加redis相關配置:

server:
  port: 9401

spring:
  application:
    name: oauth2-jwt-server
  redis:
  	# redis相關配置
    host: 10.172.0.201
    database: 0

添加在Redis中存儲令牌的配置:

@Configuration
public class RedisTokenStoreConfig {

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    @Bean
    public TokenStore redisTokenStore() {
        return new RedisTokenStore(redisConnectionFactory);
    }

}

在授權服務器配置中指定令牌的存儲策略爲Redis:

@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存儲令牌的配置:

@Configuration
public class JwtTokenStoreConfig {

    @Bean
    @Primary
    public TokenStore jwtTokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    public JwtTokenEnhancer jwtTokenEnhancer() {
        return new JwtTokenEnhancer();
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        // 配置jwt使用的密鑰
        jwtAccessTokenConverter.setSigningKey("test_key");
        return jwtAccessTokenConverter;
    }

}

在授權服務器配置中指定令牌的存儲策略爲JWT:

@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": 1577678092,
  "user_name": "jourwon",
  "authorities": [
    "admin"
  ],
  "jti": "87db4bdf-2936-420d-87b9-fb580e255a4d",
  "client_id": "admin",
  "scope": [
    "all"
  ]
}

擴展JWT中存儲的內容

有時候我們需要擴展JWT中存儲的內容,這裏我們在JWT中擴展一個key爲enhance,value爲enhance info的數據。

繼承TokenEnhancer實現一個JWT內容增強器:

public class JwtTokenEnhancer implements TokenEnhancer {

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
        Map<String, Object> info = new HashMap<>();
        info.put("enhance", "enhance info");

        ((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(info);
        return oAuth2AccessToken;
    }

}

創建一個JwtTokenEnhancer實例:

@Configuration
public class JwtTokenStoreConfig {
    
    //省略代碼...

    @Bean
    public JwtTokenEnhancer jwtTokenEnhancer() {
        return new JwtTokenEnhancer();
    }
}

在授權服務器配置中配置JWT的內容增強器:

@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;

    /**
     * 使用密碼模式需要配置
     *
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> delegates = new ArrayList<>();
        // 配置jwt內容增強器
        delegates.add(jwtTokenEnhancer);
        delegates.add(jwtAccessTokenConverter);
        tokenEnhancerChain.setTokenEnhancers(delegates);

        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(userService)
                // 配置令牌存儲策略
                .tokenStore(tokenStore)
                .accessTokenConverter(jwtAccessTokenConverter)
                .tokenEnhancer(tokenEnhancerChain);
    }

    // 省略代碼...
}

運行項目後使用密碼模式來獲取令牌,之後對令牌進行解析,發現已經包含擴展的內容。

{
  "user_name": "jourwon",
  "scope": [
    "all"
  ],
  "exp": 1577678449,
  "authorities": [
    "admin"
  ],
  "jti": "618cda6a-dfce-4966-b0df-00607f693ab5",
  "client_id": "admin",
  "enhance": "enhance info"
}

Java中解析JWT中的內容

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

在pom.xml中添加相關依賴:

<dependency>
	<groupId>io.jsonwebtoken</groupId>
	<artifactId>jjwt</artifactId>
	<version>0.9.1</version>
</dependency>

修改UserController類,使用jjwt工具類來解析Authorization頭中存儲的JWT內容。

@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的授權模式即可。

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                // 配置client_id
                .withClient("admin")
                // 配置client_secret
                .secret(passwordEncoder.encode("admin123456"))
                // 配置訪問token的有效期
                .accessTokenValiditySeconds(3600)
                // 配置刷新token的有效期
                .refreshTokenValiditySeconds(864000)
                // 配置redirect_uri,用於授權成功後的跳轉
                // .redirectUris("http://www.baidu.com")
                // 單點登錄時配置
                .redirectUris("http://localhost:9501/login")
                // 自動授權配置
                .autoApprove(true)
                // 配置申請的權限範圍
                .scopes("all")
                // 配置grant_type,表示授權類型
                .authorizedGrantTypes("authorization_code", "password", "refresh_token");
    }
}

使用刷新令牌模式來獲取新的令牌,訪問如下地址:http://localhost:9401/oauth/token

在這裏插入圖片描述

使用到的模塊

springcloud-learning
└── oauth2-jwt-server -- 使用jwt的oauth2授權測試服務

項目源碼地址

GitHub項目源碼地址

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章