<output id="qn6qe"></output>

    1. <output id="qn6qe"><tt id="qn6qe"></tt></output>
    2. <strike id="qn6qe"></strike>

      亚洲 日本 欧洲 欧美 视频,日韩中文字幕有码av,一本一道av中文字幕无码,国产线播放免费人成视频播放,人妻少妇偷人无码视频,日夜啪啪一区二区三区,国产尤物精品自在拍视频首页,久热这里只有精品12
      Fork me on GitHub

      OAuth2.0系列之密碼模式實(shí)踐教程(四)

      @

      OAuth2.0系列博客:

      1、密碼模式簡介

      1.1 前言簡介

      上一篇文章中我們學(xué)習(xí)了OAuth2的一些基本概念,對OAuth2有了基本的認(rèn)識,接著學(xué)習(xí)OAuth2.0授權(quán)模式中的密碼模式

      ps:OAuth2.0的授權(quán)模式可以分為:

      • 授權(quán)碼模式(authorization code)
      • 簡化模式(implicit)
      • 密碼模式(resource owner password credentials)
      • 客戶端模式(client credentials)

      密碼模式(resource owner password credentials):密碼模式中,用戶向客戶端提供自己的用戶名和密碼,這通常用在用戶對客戶端高度信任的情況

      1.2 授權(quán)流程圖

      官網(wǎng)圖片:
      在這里插入圖片描述

      • (A)用戶訪問客戶端,提供URI連接包含用戶名和密碼信息給授權(quán)服務(wù)器
      • (B)授權(quán)服務(wù)器對客戶端進(jìn)行身份驗(yàn)證
      • (C)授權(quán)通過,返回acceptToken給客戶端

      從調(diào)接口方面,簡單來說:

      • 第一步:直接傳username,password獲取token

      http://localhost:8888/oauth/token?client_id=cms&client_secret=secret&username=admin&password=123456&grant_type=password&scope=all

      • 第二步:拿到acceptToken之后,就可以直接訪問資源

      http://localhost:8084/api/userinfo?access_token=${accept_token}

      2、例子實(shí)踐

      2.1 實(shí)驗(yàn)環(huán)境準(zhǔn)備

      • IntelliJ IDEA
      • Maven3.+版本
        新建SpringBoot Initializer項(xiàng)目,可以命名password
        在這里插入圖片描述

      在這里插入圖片描述
      主要是想引入:

       <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-web</artifactId>
              </dependency>
       <!-- Spring Cloud Oauth2-->
              <dependency>
                  <groupId>org.springframework.cloud</groupId>
                  <artifactId>spring-cloud-starter-oauth2</artifactId>
              </dependency>
              <!-- Spring Cloud Security-->
              <dependency>
                  <groupId>org.springframework.cloud</groupId>
                  <artifactId>spring-cloud-starter-security</artifactId>
              </dependency>
      

      2.2 OAuth2.0角色

      前面的學(xué)習(xí),我們知道了OAuth2.0主要包括如下角色,下面通過代碼例子加深對理論的理解

      • 資源所有者(Resource Owner)
      • 用戶代理(User Agent)
      • 客戶端(Client)
      • 授權(quán)服務(wù)器(Authorization Server)
      • 資源服務(wù)器(Resource Server)

      生產(chǎn)環(huán)境、資源服務(wù)器和授權(quán)服務(wù)器一般是分開的,不過學(xué)習(xí)的可以放在一起

      定義資源服務(wù)器,用注解@EnableResourceServer;
      定義授權(quán)服務(wù)器,用注解@EnableAuthorizationServer;

      2.3 OAuth2.0配置類

      package com.example.oauth2.password.config;
      
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;
      import org.springframework.security.authentication.AuthenticationManager;
      import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
      import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
      import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
      import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
      import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
      import org.springframework.security.oauth2.provider.token.TokenStore;
      import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
      
      
      /**
       * <pre>
       *     OAuth2.0配置類
       * </pre>
       *
       * <pre>
       * @author mazq
       * 修改記錄
       *    修改后版本:     修改人:  修改日期: 2020/06/11 11:00  修改內(nèi)容:
       * </pre>
       */
      @Configuration
      //開啟授權(quán)服務(wù)
      @EnableAuthorizationServer
      public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
      
          @Autowired
          private AuthenticationManager authenticationManager;
      
          private static final String CLIENT_ID = "cms";
          private static final String SECRET_CHAR_SEQUENCE = "{noop}secret";
          private static final String SCOPE_READ = "read";
          private static final String SCOPE_WRITE = "write";
          private static final String TRUST = "trust";
          private static final String USER ="user";
          private static final String ALL = "all";
          private static final int ACCESS_TOKEN_VALIDITY_SECONDS = 2*60;
          private static final int FREFRESH_TOKEN_VALIDITY_SECONDS = 2*60;
          // 密碼模式授權(quán)模式
          private static final String GRANT_TYPE_PASSWORD = "password";
          //授權(quán)碼模式
          private static final String AUTHORIZATION_CODE = "authorization_code";
          //refresh token模式
          private static final String REFRESH_TOKEN = "refresh_token";
          //簡化授權(quán)模式
          private static final String IMPLICIT = "implicit";
          //指定哪些資源是需要授權(quán)驗(yàn)證的
          private static final String RESOURCE_ID = "resource_id";
      
          @Override
          public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
              clients
                      // 使用內(nèi)存存儲
                      .inMemory()
                      //標(biāo)記客戶端id
                      .withClient(CLIENT_ID)
                      //客戶端安全碼
                      .secret(SECRET_CHAR_SEQUENCE)
                      //為true 直接自動授權(quán)成功返回code
                      .autoApprove(true)
                      .redirectUris("http://127.0.0.1:8084/cms/login") //重定向uri
                      //允許授權(quán)范圍
                      .scopes(ALL)
                      //token 時(shí)間秒
                      .accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS)
                      //刷新token 時(shí)間 秒
                      .refreshTokenValiditySeconds(FREFRESH_TOKEN_VALIDITY_SECONDS)
                      //允許授權(quán)類型
                      .authorizedGrantTypes(GRANT_TYPE_PASSWORD );
          }
      
          @Override
          public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
              // 使用內(nèi)存保存生成的token
              endpoints.authenticationManager(authenticationManager).tokenStore(memoryTokenStore());
          }
      
          /**
           * 認(rèn)證服務(wù)器的安全配置
           *
           * @param security
           * @throws Exception
           */
          @Override
          public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
              security
                      //.realm(RESOURCE_ID)
                      // 開啟/oauth/token_key驗(yàn)證端口認(rèn)證權(quán)限訪問
                      .tokenKeyAccess("isAuthenticated()")
                      //  開啟/oauth/check_token驗(yàn)證端口認(rèn)證權(quán)限訪問
                      .checkTokenAccess("isAuthenticated()")
                      //允許表單認(rèn)證
                      .allowFormAuthenticationForClients();
          }
      
          @Bean
          public TokenStore memoryTokenStore() {
              // 最基本的InMemoryTokenStore生成token
              return new InMemoryTokenStore();
          }
      
      }
      
      
      
      

      2.4 Security配置類

      為了測試,可以進(jìn)行簡單的SpringSecurity

      package com.example.oauth2.password.config;
      
      
      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;
      import org.springframework.core.annotation.Order;
      import org.springframework.security.authentication.AuthenticationManager;
      import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
      import org.springframework.security.config.annotation.web.builders.HttpSecurity;
      import org.springframework.security.config.annotation.web.builders.WebSecurity;
      import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
      import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
      
      /**
       * <pre>
       *  SpringSecurity配置類
       * </pre>
       *
       * <pre>
       * @author mazq
       * 修改記錄
       *    修改后版本:     修改人:  修改日期: 2020/06/11 11:23  修改內(nèi)容:
       * </pre>
       */
      @Configuration
      @EnableWebSecurity
      @Order(1)
      public class SecurityConfig extends WebSecurityConfigurerAdapter {
      
          @Bean
          @Override
          public AuthenticationManager authenticationManagerBean() throws Exception {
              return super.authenticationManagerBean();
          }
      
          @Override
          protected void configure(AuthenticationManagerBuilder auth) throws Exception {    //auth.inMemoryAuthentication()
              auth.inMemoryAuthentication()
                      .withUser("nicky")
                      .password("{noop}123")
                      .roles("admin");
          }
      
          @Override
          public void configure(WebSecurity web) throws Exception {
              //解決靜態(tài)資源被攔截的問題
              web.ignoring().antMatchers("/asserts/**");
              web.ignoring().antMatchers("/favicon.ico");
          }
      
          @Override
          protected void configure(HttpSecurity http) throws Exception {
              http   // 配置登錄頁并允許訪問
                      //.formLogin().permitAll()
                      // 配置Basic登錄
                      //.and().httpBasic()
                      // 配置登出頁面
                      .logout().logoutUrl("/logout").logoutSuccessUrl("/")
                      // 配置允許訪問的鏈接
                      .and().authorizeRequests().antMatchers("/oauth/**", "/login/**", "/logout/**","/api/**").permitAll()
                      // 其余所有請求全部需要鑒權(quán)認(rèn)證
                      .anyRequest().authenticated()
                      // 關(guān)閉跨域保護(hù);
                      .and().csrf().disable();
          }
      
      }
      
      
      

      2.5 功能簡單測試

      接口測試,要用POST方式,在postman測試,response_type參數(shù)傳password:

      http://localhost:8888/oauth/token?password=123&grant_type=password&username=nicky&scope=all

      在這里插入圖片描述

      注意配置一下請求頭的授權(quán)參數(shù),username即client_id,password即client_secret
      在這里插入圖片描述

      代碼方式請求,可以進(jìn)行如下封裝,即進(jìn)行base64加密

      HttpHeaders headers = new HttpHeaders();
              byte[] key = (clientId+":"+clientSecret).getBytes();
              String authKey = new String(Base64.encodeBase64(key));
              LOG.info("Authorization:{}","Basic "+authKey);
              headers.add("Authorization","Basic "+authKey);
      

      拿到token直接去調(diào)業(yè)務(wù)接口:
      http://localhost:8888/api/userinfo?access_token=61b113f3-f1e2-473e-a6d7-a0264bfdfa8d

      例子代碼下載:code download

      posted @ 2020-06-11 17:42  smileNicky  閱讀(3355)  評論(0)    收藏  舉報(bào)
      主站蜘蛛池模板: 久草网视频在线观看| 日本一道高清一区二区三区| 久久久久影院色老大2020| 国产一区国产二区在线视频 | 99在线精品视频观看免费| 国产精品久久久久久久久久直播| 国产农村激情免费专区| 一区二区在线观看 激情| 国产午夜亚洲精品福利| 亚洲中文字幕日产无码成人片| 中文字幕人妻中文AV不卡专区| 麻豆亚洲精品一区二区| 欧美亚洲国产精品久久| 狼色精品人妻在线视频| 成 人 色 网 站免费观看| 亚洲高清WWW色好看美女| 国产嫩草精品网亚洲av| 九九热在线免费播放视频| 亚洲 日本 欧洲 欧美 视频| 国产91色综合久久免费| 色国产视频| 国产免费午夜福利蜜芽无码| 4399理论片午午伦夜理片| 久久人人爽人人爽人人片av| 亚洲 另类 小说 国产精品无码| 国产精品亚洲二区在线播放| 美女无遮挡免费视频网站| 国产精品一线二线三线区| 国产欧美精品一区aⅴ影院| 亚洲国产成人久久一区久久| 日韩狼人精品在线观看| 欧美成人性色一区欧美成人性色区| 国产精品无码久久久久AV| 蜜臀av入口一区二区三区| 风间由美性色一区二区三区| 久久精品蜜芽亚洲国产av| 亚洲成av人片色午夜乱码| 婷婷99视频精品全部在线观看| 成人午夜激情在线观看| 男女性杂交内射女bbwxz| 亚洲国产午夜精品福利|