1. 程式人生 > 程式設計 >Spring Security 解析(五) —— Spring Security Oauth2 開發

Spring Security 解析(五) —— Spring Security Oauth2 開發

Spring Security 解析(五) —— Spring Security Oauth2 開發

  在學習Spring Cloud 時,遇到了授權服務oauth 相關內容時,總是一知半解,因此決定先把Spring Security 、Spring Security Oauth2 等許可權、認證相關的內容、原理及設計學習並整理一遍。本系列文章就是在學習的過程中加強印象和理解所撰寫的,如有侵權請告知。

專案環境:

- JDK1.8

- Spring boot 2.x

- Spring Security 5.x

  前面幾篇文章基本上已經把Security的核心內容講得差不多了,那麼從本篇文章我們開始接觸Spring Security Oauth2 相關的內容,這其中包括後面的 Spring Social (其本質也是基於Oauth2)。有一點要說明的是,我們是在原有的Spring-Security 專案上繼續開發,存在一些必要的重構,但不影響前面Security的功能。

一、 Oauth2 與 Spring Security Oauth2

Oauth2

  有關於Oauth2 的 資料,網上很多,但最值得推薦的還是 阮一峰老師的 理解OAuth 2.0,在這裡我就不重複描述Oauth2了,但我還是有必要提下其中的重要的點:https://user-gold-cdn.xitu.io/2019/9/16/16d38a4606bb13d4?w=948&h=468&f=jpeg&s=172612

  圖片中展示的流程是授權碼模式的流程,其中最核心正如圖片展示的一樣:

  • 資源所有者(Resource Owner): 可以理解為使用者
  • 服務提供商(Provider): 分為認證伺服器(Authorization server)和 資源伺服器(Resource server)。怎麼理解認證、資源伺服器呢,很簡單,比如我們手機某個APP通過QQ來登陸,在我們跳轉到一個QQ授權的頁面以及登陸的操作都是在認證伺服器上做的,後面我們登陸成功後能夠看到我們的頭像等資訊,這些資訊就是登陸成功後去資源伺服器獲取到的。
  • 第三方應用: 可以理解就是我們正在使用的某個APP,使用者通過這個APP發起QQ授權登陸。

Spring Security Oauth2

   Spring 官方出品的 一個實現 Oauth2 協議的技術框架,後面的系列文章其實都是在解析它是如何實現Oauth2的。如果各位有時間的話可以看下Spring Security Oauth2 官方檔案,我的文章分析也是依靠檔案來的。

  最後,我個人總結這2者的區別:

  • Oauth2 不是一門技術框架, 而是一個協議,它僅僅只是制定好了協議的標準設計思想,你可以用Java實現,也可以用其他任何語言實現。
  • Spring Security Oauth2 是一門技術框架,它是依據Oauth2協議開發出來的。

一、 Spring Security Oauth2 開發

   在微服務開發的過程中,一般會把授權伺服器和資源伺服器拆分成2個應用程式,所以本專案採用這種設計結構,不過在開發前,我們需要做一步重要得步驟,就是專案重構。

一、 專案重構

   為什麼要重構呢?因為我們是將授權和資源2個伺服器拆分了,之前開發的一些配置和功能是可以在2個伺服器共用的,所以我們可以講公共的配置和功能可以單獨羅列出來,以及後面我們開發Spring Security Oauth2 得一些公共配置(比如Token相關配置)。 我們新建 security-core 子模組,將之前開發的簡訊等功能程式碼遷移到這個子模組中。最終得到以下專案結構:

https://user-gold-cdn.xitu.io/2019/9/16/16d38a46e5c02e8f?w=486&h=700&f=jpeg&s=173604

   遷移完成後,原先專案模組更換模組名為 security-oauth2-authorization ,即 授權服務應用,並且 在pom.xml 中引用 security-core 依賴,遷移後該模組的專案結構如下:

https://user-gold-cdn.xitu.io/2019/9/16/16d38a4733ce15f2?w=457&h=501&f=jpeg&s=102047

   我們可以發現,遷移後的專案內部只有 Security相關的配置程式碼和測試介面,以及靜態的html。

二、 授權伺服器開發

一、Maven依賴

  在 security-core 模組的pom.xml 中引用 以下依賴:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-jwt</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- 不是starter,手動配置 -->
        <dependency>
            <groupId>org.springframework.security.oauth</groupId>
            <artifactId>spring-security-oauth2</artifactId>
            <!--請注意下 spring-authorization-oauth2 的版本 務必高於 2.3.2.RELEASE,這是官方的一個bug:
            java.lang.NoSuchMethodError: org.springframework.data.redis.connection.RedisConnection.set([B[B)V
            要求必須大於2.3.5 版本,官方解釋:https://github.com/BUG9/spring-security/network/alert/pom.xml/org.springframework.security.oauth:spring-security-oauth2/open
            -->
            <version>2.3.5.RELEASE</version>
        </dependency>複製程式碼

  這裡新增 spring-security-oauth2 依賴,一個針對token 的儲存策略分別引用了 redis 和 jwt 依賴。

注意這裡 spring-security-oauth2 版本必須高於 2.3.5 版本 ,否自使用 redis 儲存token 策略會報出:
org.springframework.data.redis.connection.RedisConnection.set([B[B)V 異常

   security-oauth2-authorization 模組的 pom 引用 security-core :

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!-- 這裡去掉 spring-security-oauth2 主要是其內部的版本是 低於2.3.5
        (security-core 本身 引用的就是 2.3.5 ,但為什麼這邊看到的卻是低於其版本,暫時沒找到原因,可能統一版本管理 platform-bom 的問題吧)
         ,為了防止出現異常這裡去掉,再單獨引用-->
        <dependency>
            <groupId>com.zhc</groupId>
            <artifactId>security-core</artifactId>
            <version>0.0.1-SNAPSHOT</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.security.oauth</groupId>
                    <artifactId>spring-security-oauth2</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- 不是starter,手動配置 -->
        <dependency>
            <groupId>org.springframework.security.oauth</groupId>
            <artifactId>spring-security-oauth2</artifactId>
            <!--請注意下 spring-authorization-oauth2 的版本 務必高於 2.3.2.RELEASE,這是官方的一個bug:
            java.lang.NoSuchMethodError: org.springframework.data.redis.connection.RedisConnection.set([B[B)V
            要求必須大於2.3.5 版本,官方解釋:https://github.com/BUG9/spring-security/network/alert/pom.xml/org.springframework.security.oauth:spring-security-oauth2/open
            -->
            <version>2.3.5.RELEASE</version>
        </dependency>複製程式碼

二、配置授權認證 @EnableAuthorizationServer

  在Spring Security Oauth2 中有一個 @EnableAuthorizationServer ,只要我們 在專案中引用到了這個註解,那麼一個基本的授權服務就配置好了,但是實際專案中並不這樣做。比如要配置redis和jwt 2種儲存token策略共存,通過繼承 AuthorizationServerConfigurerAdapter 來實現。 下列程式碼是我的一個個性化配置:

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    @Resource
    private AuthenticationManager authenticationManager;  // 1、引用 authenticationManager 支援 Password 授權模式

    private final Map<String,TokenStore> tokenStoreMap; // 2、獲取到系統所有的 token儲存策略物件 TokenStore ,這裡我配置了 redisTokenStore 和 jwtTokenStore

    @Autowired(required = false)
    private AccessTokenConverter jwtAccessTokenConverter; // 3、 jwt token的增強器

    /**
     *  4、由於儲存策略時根據配置指定的,當使用redis策略時,tokenEnhancerChain 是沒有被注入的,所以這裡設定成 required = false
      */
    @Autowired(required = false)
    private TokenEnhancerChain tokenEnhancerChain; // 5、token的增強器鏈

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Value("${spring.security.oauth2.storeType}")
    private String storeType = "jwt";  // 6、通過獲取配置來判斷當前使用哪種儲存策略,預設jwt

    @Autowired
    public AuthorizationServerConfiguration(Map<String,TokenStore> tokenStoreMap) {
        this.tokenStoreMap = tokenStoreMap;
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        //7、 配置一個客戶端,支援客戶端模式、密碼模式和授權碼模式
        clients.inMemory()  // 採用記憶體方式。也可以採用 資料庫方式
                .withClient("client1") // clientId 
                .authorizedGrantTypes("client_credentials","password","authorization_code","refresh_token") // 授權模式
                .scopes("read") // 許可權範圍 
                .redirectUris("http://localhost:8091/login") // 授權碼模式返回code碼的回撥地址
                // 自動授權,無需人工手動點選 approve
                .autoApprove(true)  
                .secret(passwordEncoder.encode("123456"))
                .and()
                .withClient("client2")
                .authorizedGrantTypes("client_credentials","refresh_token")
                .scopes("read")
                .redirectUris("http://localhost:8092/login")
                .autoApprove(true)
                .secret(passwordEncoder.encode("123456"));
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // 設定token儲存方式,這裡提供redis和jwt
        endpoints
                .tokenStore(tokenStoreMap.get(storeType + "TokenStore"))
                .authenticationManager(authenticationManager);
        if ("jwt".equalsIgnoreCase(storeType)) {
            endpoints.accessTokenConverter(jwtAccessTokenConverter)
                    .tokenEnhancer(tokenEnhancerChain);
        }
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer// 開啟/oauth/token_key驗證埠無許可權訪問
                .tokenKeyAccess("permitAll()")
                // 開啟/oauth/check_token驗證埠認證許可權訪問
                .checkTokenAccess("isAuthenticated()")
                //允許表單認證    請求/oauth/token的,如果配置支援allowFormAuthenticationForClients的,且url中有client_id和client_secret的會走ClientCredentialsTokenEndpointFilter
                .allowFormAuthenticationForClients();
    }
}複製程式碼

  這裡的配置分3部分:

  • ClientDetailsServiceConfigurer: 配置客戶端資訊。 可以採用記憶體方式、JDBC方式等等,我們還可以像UserDetailsService一樣定製ClientDetailsService。
  • AuthorizationServerEndpointsConfigurer : 配置 授權節點資訊。這裡主要配置 tokenStore
  • AuthorizationServerSecurityConfigurer: 授權節點的安全配置。 這裡開啟/oauth/tokenkey驗證埠無許可權訪問(單點客戶端啟動時會呼叫該介面獲取jwt的key,所以這裡設定成無許可權訪問)以及 /oauth/token配置支援allowFormAuthenticationForClients(url中有clientid和client_secret的會走ClientCredentialsTokenEndpointFilter)
三、配置 TokenStore

  在配置授權認證時,依賴注入了 tokenStore 、jwtAccessTokenConverter、tokenEnhancerChain,但這些物件是如何配置並注入到Spring 容器的呢?且看下面程式碼:

@Configuration
public class TokenStoreConfig {
    /**
     * redis連線工廠
     */
    @Resource
    private RedisConnectionFactory redisConnectionFactory;

    /**
     * 使用redisTokenStore儲存token
     *
     * @return tokenStore
     */
    @Bean
    @ConditionalOnProperty(prefix = "spring.security.oauth2",name = "storeType",havingValue = "redis")
    public TokenStore redisTokenStore() {
        return new RedisTokenStore(redisConnectionFactory);
    }

    @Bean
    PasswordEncoder passwordEncoder(){
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    /**
     * jwt的配置
     *
     * 使用jwt時的配置,預設生效
     */
    @Configuration
    @ConditionalOnProperty(prefix = "spring.security.oauth2",havingValue = "jwt",matchIfMissing = true)
    public static class JwtTokenConfig {

        @Resource
        private SecurityProperties securityProperties;
        /**
         * 使用jwtTokenStore儲存token
         * 這裡通過 matchIfMissing = true 設定預設使用 jwtTokenStore
         *
         * @return tokenStore
         */
        @Bean
        public TokenStore jwtTokenStore() {
            return new JwtTokenStore(jwtAccessTokenConverter());
        }

        /**
         * 用於生成jwt
         *
         * @return JwtAccessTokenConverter
         */
        @Bean
        public JwtAccessTokenConverter jwtAccessTokenConverter() {
            JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter();
            //生成簽名的key,這裡使用對稱加密
            accessTokenConverter.setSigningKey(securityProperties.getOauth2().getJwtSigningKey());
            return accessTokenConverter;
        }

        /**
         * 用於擴充套件JWT
         *
         * @return TokenEnhancer
         */
        @Bean
        @ConditionalOnMissingBean(name = "jwtTokenEnhancer")
        public TokenEnhancer jwtTokenEnhancer() {
            return new JwtTokenEnhance();
        }

        /**
         * 自定義token擴充套件鏈
         *
         * @return tokenEnhancerChain
         */
        @Bean
        public TokenEnhancerChain tokenEnhancerChain() {
            TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
            tokenEnhancerChain.setTokenEnhancers(Arrays.asList(new JwtTokenEnhance(),jwtAccessTokenConverter()));
            return tokenEnhancerChain;
        }
    }
}複製程式碼

  注意: 該配置類適用於均適用於授權和資源伺服器,所以該配置類是放在 security-core 模組

四、新增 application.yml 配置
 spring:
   redis:
     host: 127.0.0.1
     port: 6379
   security:
     oauth2:
       storeType: redis
       jwt:
         SigningKey: oauth2複製程式碼

五、啟動測試

1、 授權碼模式:granttype=authorizationcode

  (1)瀏覽器上訪問/oauth/authorize 獲取授權碼:

http://localhost:9090/oauth/authorize?response_type=code&client_id=client1&scope=read&state=test&redirect_uri=http://localhost:8091/login複製程式碼

如果是沒有登陸過,則跳轉到登陸介面(這裡賬戶密碼登陸和簡訊驗證碼登陸均可),成功跳轉到 我們設定的回撥地址(我們這個是單點登陸客戶端),我們可以從瀏覽器位址列看到 code碼

  (2)Postman請求/oauth/token 獲取token:

localhost:9090/oauth/token?grant_type=authorization_code&code=i4ge7B&redirect_uri=http://localhost:8091/login複製程式碼

https://user-gold-cdn.xitu.io/2019/9/16/16d38a4793f34044?w=994&h=539&f=jpeg&s=165732

   注意在 Authorization 填寫 client資訊,下面是 curl 請求:

curl -X POST \
  'http://localhost:9090/oauth/token?grant_type=authorization_code&code=Q38nnC&redirect_uri=http://localhost:8091/login' \
  -H 'Accept: */*' \
  -H 'Accept-Encoding: gzip,deflate' \
  -H 'Authorization: Basic Y2xpZW50MToxMjM0NTY=' \
  -H 'Cache-Control: no-cache' \
  -H 'Connection: keep-alive' \
  -H 'Content-Length: ' \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -H 'Cookie: remember-me=; JSESSIONID=F6F6DE2968113DDE4613091E998D77F4' \
  -H 'Host: localhost:9090' \
  -H 'Postman-Token: f37b9921-4efe-44ad-9884-f14e9bd74bce,3c80ffe3-9e1c-4222-a2e1-9694bff3510a' \
  -H 'User-Agent: PostmanRuntime/7.16.3' \
  -H 'cache-control: no-cache'複製程式碼

   響應報文:

 {
     "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiI5MDAxIiwic2NvcGUiOlsicmVhZCJdLCJleHAiOjE1Njg2NDY0NzksImF1dGhvcml0aWVzIjpbImFkbWluIl0sImp0aSI6ImY5ZDBhNmZhLTAxOWYtNGU5Ny1iMmI4LWI1OTNlNjBiZjk0NiIsImNsaWVudF9pZCI6ImNsaWVudDEiLCJ1c2VybmFtZSI6IjkwMDEifQ.4BjG_LggZt2RJr0VzXTSmsk71EIUDGvrQsL_OPsg8VA","token_type": "bearer","refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiI5MDAxIiwic2NvcGUiOlsicmVhZCJdLCJhdGkiOiJmOWQwYTZmYS0wMTlmLTRlOTctYjJiOC1iNTkzZTYwYmY5NDYiLCJleHAiOjE1NzExOTUyNzksImF1dGhvcml0aWVzIjpbImFkbWluIl0sImp0aSI6IjU1NTRmYjdkLTBhZGItNGI4MS1iOGNlLWIwOTk2NjM1OTI4MCIsImNsaWVudF9pZCI6ImNsaWVudDEiLCJ1c2VybmFtZSI6IjkwMDEifQ.TA1frc46XRkNgl3Y_n72rM0nZ5QceWH3zJFmR7CkHQ4","expires_in": 43199,"scope": "read","username": "9001","jti": "f9d0a6fa-019f-4e97-b2b8-b593e60bf946"
 }複製程式碼

2、 密碼模式: grant_type=password

Postman:

    http://localhost:9090/oauth/token?username=user&password=123456&grant_type=password&scope=read&client_id=client1&client_secret=123456複製程式碼

curl:

 curl -X POST \
   'http://localhost:9090/oauth/token?username=user&password=123456&grant_type=password&scope=read&client_id=client1&client_secret=123456' \
   -H 'Accept: */*' \
   -H 'Accept-Encoding: gzip,deflate' \
   -H 'Cache-Control: no-cache' \
   -H 'Connection: keep-alive' \
   -H 'Content-Length: ' \
   -H 'Cookie: remember-me=; JSESSIONID=F6F6DE2968113DDE4613091E998D77F4' \
   -H 'Host: localhost:9090' \
   -H 'Postman-Token: f41c7e67-1127-4b65-87ed-21b3e00cfae3,08168e2e-1818-42f8-b4c4-cafd4aa0edc4' \
   -H 'User-Agent: PostmanRuntime/7.16.3' \
   -H 'cache-control: no-cache'
   複製程式碼


3、 客戶端模式 : granttype=clientcredentials

Postman:

    localhost:9090/oauth/token?scope=read&grant_type=client_credentials複製程式碼

   注意在 Authorization 填寫 client資訊,下面是 curl 請求:

curl:

 curl -X POST \
   'http://localhost:9090/oauth/token?scope=read&grant_type=client_credentials' \
   -H 'Accept: */*' \
   -H 'Accept-Encoding: gzip,deflate' \
   -H 'Authorization: Basic Y2xpZW50MToxMjM0NTY=' \
   -H 'Cache-Control: no-cache' \
   -H 'Connection: keep-alive' \
   -H 'Content-Length: 35' \
   -H 'Content-Type: application/x-www-form-urlencoded' \
   -H 'Cookie: remember-me=; JSESSIONID=F6F6DE2968113DDE4613091E998D77F4' \
   -H 'Host: localhost:9090' \
   -H 'Postman-Token: a8d3b4a2-7aee-4f0d-8959-caa99a412012,f5e41385-b2b3-48d2-aa65-8b1d1c075cab' \
   -H 'User-Agent: PostmanRuntime/7.16.3' \
   -H 'cache-control: no-cache' \
   -d 'username=zhoutaoo&password=password'
 複製程式碼

   授權服務開發,我們繼續延用之前的security配置,包括 UserDetailsService及其登陸配置,在其基礎上我們新增了授權配置,完成整個授權服務的搭建及測試。

三、 資源伺服器開發

  由於資源伺服器是個許可權的應用程式,我們新建 security-oauth2-authentication 子模組作為資源伺服器應用。

一、Maven依賴

   security-oauth2-authentication 模組 pom 引用 security-core:

        <dependency>
            <groupId>com.zhc</groupId>
            <artifactId>security-core</artifactId>
            <version>0.0.1-SNAPSHOT</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.security.oauth</groupId>
                    <artifactId>spring-security-oauth2</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- 不是starter,手動配置 -->
        <dependency>
            <groupId>org.springframework.security.oauth</groupId>
            <artifactId>spring-security-oauth2</artifactId>
            <!--請注意下 spring-authorization-oauth2 的版本 務必高於 2.3.2.RELEASE,這是官方的一個bug:
            java.lang.NoSuchMethodError: org.springframework.data.redis.connection.RedisConnection.set([B[B)V
            要求必須大於2.3.5 版本,官方解釋:https://github.com/BUG9/spring-security/network/alert/pom.xml/org.springframework.security.oauth:spring-security-oauth2/open
            -->
            <version>2.3.5.RELEASE</version>
        </dependency>複製程式碼

二、配置授權服務 @EnableResourceServer

   整個資源服務的配置主要分3個點:

  • @EnableResourceServer 必須的,是整個資源伺服器的基礎
  • tokenStore 由於授權伺服器採用了不同的tokenStore,所以我們解析token也得根據配置的儲存策略來
  • HttpSecurity 一般來說只要是資源伺服器,其內部的介面均需要認證後才可訪問,這裡簡單配置了以下。
@Configuration
@EnableResourceServer  // 1
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    private final Map<String,TokenStore> tokenStoreMap;

    @Value("${spring.security.oauth2.storeType}")
    private String storeType = "jwt";

    @Autowired
    public ResourceServerConfiguration(Map<String,TokenStore> tokenStoreMap) {
        this.tokenStoreMap = tokenStoreMap;
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.tokenStore(tokenStoreMap.get(storeType + "TokenStore"));  //  2
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .requestMatchers().anyRequest()
                .and()
                .anonymous()
                .and()
                .authorizeRequests()
                //配置oauth2訪問(測試介面)控制,必須認證過後才可以訪問
                .antMatchers("/oauth2/**").authenticated();  // 3 
    }
}複製程式碼

三、配置 application.yml

   由於授權伺服器採用不同tokenStore,所以這裡也要引用 其 配置:

spring:
  redis:
    host: 127.0.0.1
    port: 6379
  security:
    oauth2:
      storeType: jwt
      jwt:
        SigningKey: oauth2複製程式碼

四、測試介面

 
 @RestController
 @RequestMapping("/oauth2")
 @EnableGlobalMethodSecurity(prePostEnabled = true)
 @Slf4j
 public class TestEndpoints {
 
     @GetMapping("/getUser")
     @PreAuthorize("hasAnyAuthority('user')")
     public String getUser() {
         Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
         return "User: " + authentication.getPrincipal().toString();
     }
 }
 複製程式碼

五、啟動測試

   我們將從授權伺服器獲取到的token進行訪問測試介面:

Postman:

    http://localhost:8090/oauth2/getUser?access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJyZWFkIl0sImV4cCI6MTU2ODY0ODEyMCwianRpIjoiNDQ0NWQ1ZDktYWZlMC00N2Y1LTk0NGItZTEyNzI1NzI1M2M1IiwiY2xpZW50X2lkIjoiY2xpZW50MSIsInVzZXJuYW1lIjoiY2xpZW50MSJ9.pOnIcmjy2ex7jlXvAGslEN89EyFPYPbW-l4f_cyK17k複製程式碼

curl:

  
 curl -X GET \
   'http://localhost:8090/oauth2/getUser?access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJyZWFkIl0sImV4cCI6MTU2ODY0ODEyMCwianRpIjoiNDQ0NWQ1ZDktYWZlMC00N2Y1LTk0NGItZTEyNzI1NzI1M2M1IiwiY2xpZW50X2lkIjoiY2xpZW50MSIsInVzZXJuYW1lIjoiY2xpZW50MSJ9.pOnIcmjy2ex7jlXvAGslEN89EyFPYPbW-l4f_cyK17k' \
   -H 'Accept: */*' \
   -H 'Accept-Encoding: gzip,deflate' \
   -H 'Cache-Control: no-cache' \
   -H 'Connection: keep-alive' \
   -H 'Cookie: remember-me=; JSESSIONID=F6F6DE2968113DDE4613091E998D77F4' \
   -H 'Host: localhost:8090' \
   -H 'Postman-Token: 07ec53c7-9051-439b-9603-ef0fe93664fa,e4a5b46e-feb7-4bf8-ab53-0c33aa44f661' \
   -H 'User-Agent: PostmanRuntime/7.16.3' \
   -H 'cache-control: no-cache'
  複製程式碼

四、 個人總結

   Spring security Oauth2 就是一套標準的Oauth2實現,我們可以通過開發進一步的瞭解Oauth2的,但整體上涉及到的技術還是很多的,比如redis、jwt等等。本文僅僅只是簡單的演示Spring security Oauth2 Demo,希望對你有幫助,如果你還對想深入解析下Spring Security Oauth2,那麼請繼續關注我,後續會解析其原理。

   本文介紹Spring security Oauth2開發的程式碼可以訪問程式碼倉庫 ,專案的github 地址 : https://github.com/BUG9/spring-security

         如果您對這些感興趣,歡迎star、follow、收藏、轉發給予支援!