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

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

  在學習Spring Cloud 時,遇到了受權服務oauth 相關內容時,老是隻知其一;不知其二,所以決定先把Spring Security 、Spring Security Oauth2 等權限、認證相關的內容、原理及設計學習並整理一遍。本系列文章就是在學習的過程當中增強印象和理解所撰寫的,若有侵權請告知。html

項目環境:java

- JDK1.8mysql

- Spring boot 2.xgit

- Spring Security 5.xgithub

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

1、 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=172612spring

  圖片中展現的流程是受權碼模式的流程,其中最核心正如圖片展現的同樣:sql

  • 資源全部者(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協議開發出來的。

1、 Spring Security Oauth2 開發

   在微服務開發的過程當中,通常會把受權服務器和資源服務器拆分紅2個應用程序,因此本項目採用這種設計結構,不過在開發前,咱們須要作一步重要得步驟,就是項目重構。

1、 項目重構

   爲何要重構呢?由於咱們是將受權和資源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。

2、 受權服務器開發

1、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>複製代碼

2、配置受權認證 @EnableAuthorizationServer

  在Spring Security Oauth2 中有一個 @EnableAuthorizationServer ,只要咱們 在項目中引用到了這個註解,那麼一個基本的受權服務就配置好了,可是實際項目中並不這樣作。好比要配置redis和jwt 2種存儲token策略共存,經過繼承 AuthorizationServerConfigurerAdapter 來實現。 下列代碼是個人一個個性化配置:

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    @Resource
    private AuthenticationManager authenticationManager;  // 一、引用 authenticationManager 支持 Password 受權模式

    private final Map<String, TokenStore> tokenStoreMap; // 二、獲取到系統全部的 token存儲策略對象 TokenStore ,這裏我配置了 redisTokenStore 和 jwtTokenStore

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

    /**
     *  四、因爲存儲策略時根據配置指定的,當使用redis策略時,tokenEnhancerChain 是沒有被注入的,因此這裏設置成 required = false
      */
    @Autowired(required = false)
    private TokenEnhancerChain tokenEnhancerChain; // 五、token的加強器鏈

    @Autowired
    private PasswordEncoder passwordEncoder;

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

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

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        //七、 配置一個客戶端,支持客戶端模式、密碼模式和受權碼模式
        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", "password", "authorization_code", "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)
3、配置 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", name = "storeType", 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 模塊

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

5、啓動測試

一、 受權碼模式: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"
 }複製代碼

二、 密碼模式: 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'
   複製代碼


三、 客戶端模式 : 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及其登錄配置,在其基礎上咱們新增了受權配置,完成整個受權服務的搭建及測試。

3、 資源服務器開發

  因爲資源服務器是個權限的應用程序,咱們新建 security-oauth2-authentication 子模塊做爲資源服務器應用。

1、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>複製代碼

2、配置受權服務 @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 
    }
}複製代碼

3、配置 application.yml

   因爲受權服務器採用不一樣tokenStore,因此這裏也要引用 其 配置:

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

4、測試接口

@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();
     }
 }
 複製代碼

5、啓動測試

   咱們將從受權服務器獲取到的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'
  複製代碼

4、 我的總結

   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、收藏、轉發給予支持!

相關文章
相關標籤/搜索