IdentityServer4系列 | 受權碼模式

1、前言

在上一篇關於簡化模式中,經過客戶端以瀏覽器的形式請求IdentityServer服務獲取訪問令牌,從而請求獲取受保護的資源,但因爲token攜帶在url中,安全性方面不能保證。所以,咱們能夠考慮經過其餘方式來解決這個問題。html

咱們經過Oauth2.0的受權碼模式瞭解,這種模式不一樣於簡化模式,在於受權碼模式不直接返回token,而是先返回一個受權碼,而後再根據這個受權碼去請求token。這顯得更爲安全。git

因此在這一篇中,咱們將經過多種受權模式中的受權碼模式進行說明,主要針對介紹IdentityServer保護API的資源,受權碼訪問API資源。github

2、初識


(圖片來源網絡)數據庫

指的是第三方應用先申請一個受權碼,而後再用該碼獲取令牌,實現與資源服務器的通訊。json

看一個常見的QQ登錄第三方網站的流程以下圖所示:c#

2.1 適用範圍

受權碼模式(authorization code)是功能最完整、流程最嚴密的受權模式。後端

受權碼模式適用於有後端的應用,由於客戶端根據受權碼去請求token時是須要把客戶端密碼轉進來的,爲了不客戶端密碼被暴露,因此請求token這個過程須要放在後臺。api

2.2 受權流程:

+----------+
     | Resource |
     |   Owner  |
     |          |
     +----------+
          ^
          |
         (B)
     +----|-----+          Client Identifier      +---------------+
     |         -+----(A)-- & Redirection URI ---->|               |
     |  User-   |                                 | Authorization |
     |  Agent  -+----(B)-- User authenticates --->|     Server    |
     |          |                                 |               |
     |         -+----(C)-- Authorization Code ---<|               |
     +-|----|---+                                 +---------------+
       |    |                                         ^      v
      (A)  (C)                                        |      |
       |    |                                         |      |
       ^    v                                         |      |
     +---------+                                      |      |
     |         |>---(D)-- Authorization Code ---------'      |
     |  Client |          & Redirection URI                  |
     |         |                                             |
     |         |<---(E)----- Access Token -------------------'
     +---------+       (w/ Optional Refresh Token)

受權碼受權流程描述瀏覽器

(A)用戶訪問第三方應用,第三方應用將用戶導向認證服務器安全

(B)用戶選擇是否給予第三方應用受權

(C)假設用戶給予受權,認證服務器將用戶導向第三方應用事先指定的重定向URI,同時帶上一個受權碼

(D)第三方應用收到受權碼,帶上上一步時的重定向URI,向認證服務器申請訪問令牌。這一步是在第三方應用的後臺的服務器上完成的,對用戶不可見

(E)認證服務器覈對了受權碼和重定向URI,確認無誤後,向第三方應用發送訪問令牌(Access Token)和更新令牌(Refresh token)

(F)訪問令牌過時後,刷新訪問令牌

2.2.1 過程詳解


訪問令牌請求
(1)用戶訪問第三方應用,第三方應用將用戶導向認證服務器
(用戶的操做:用戶訪問https://client.example.com/cb跳轉到登陸地址,選擇受權服務器方式登陸)

在受權開始以前,它首先生成state參數(隨機字符串)。client端將須要存儲這個(cookie,會話或其餘方式),以便在下一步中使用。

GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz
        &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1
HTTP/1.1 Host: server.example.com

生成的受權URL如上所述(如上),請求這個地址後重定向訪問受權服務器,其中 response_type參數爲code,表示受權類型,返回code受權碼。

參數 是否必須 含義
response_type 必需 表示受權類型,此處的值固定爲"code"
client_id 必需 客戶端ID
redirect_uri 可選 表示重定向的URI
scope 可選 表示受權範圍。
state 可選 表示隨機字符串,可指定任意值,認證服務器會返回這個值

(2)假設用戶給予受權,認證服務器將用戶導向第三方應用事先指定的重定向URI,同時帶上一個受權碼

HTTP/1.1 302 Found
Location: https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA&state=xyz
參數 含義
code 表示受權碼,必選項。該碼的有效期應該很短,一般設爲10分鐘,客戶端只能使用該碼一次,不然會被受權服務器拒絕。該碼與客戶端ID和重定向URI,是一一對應關係。
state 若是客戶端的請求中包含這個參數,認證服務器的迴應也必須如出一轍包含這個參數。

(3)第三方應用收到受權碼,帶上上一步時的重定向URI,向認證服務器申請訪問令牌。這一步是在第三方應用的後臺的服務器上完成的,對用戶不可見

POST /token HTTP/1.1
Host: server.example.com
Authorization: Bearer czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA
&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb
參數 含義
grant_type 表示使用的受權模式,必選項,此處的值固定爲"authorization_code"。
code 表示上一步得到的受權碼,必選項。
redirect_uri 表示重定向URI,必選項,且必須與步驟1中的該參數值保持一致。
client_id 表示客戶端ID,必選項。

(4)認證服務器覈對了受權碼和重定向URI,確認無誤後,向第三方應用發送訪問令牌(Access Token)和更新令牌(Refresh token)

HTTP/1.1 200 OK
     Content-Type: application/json;charset=UTF-8
     Cache-Control: no-store
     Pragma: no-cache
     {
       "access_token":"2YotnFZFEjr1zCsicMWpAA",
       "token_type":"Bearer",
       "expires_in":3600,
       "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",
       "example_parameter":"example_value"
     }
參數 含義
access_token 表示訪問令牌,必選項。
token_type 表示令牌類型,該值大小寫不敏感,必選項,能夠是Bearer類型或mac類型。
expires_in 表示過時時間,單位爲秒。若是省略該參數,必須其餘方式設置過時時間。
refresh_token 表示更新令牌,用來獲取下一次的訪問令牌,可選項。
scope 表示權限範圍,若是與客戶端申請的範圍一致,此項可省略。

(5) 訪問令牌過時後,刷新訪問令牌

POST /token HTTP/1.1
Host: server.example.com
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded
grant_type=refresh_token&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA
參數 含義
granttype 表示使用的受權模式,此處的值固定爲"refreshtoken",必選項。
refresh_token 表示早前收到的更新令牌,必選項。
scope 表示申請的受權範圍,不能夠超出上一次申請的範圍,若是省略該參數,則表示與上一次一致。

3、實踐

在示例實踐中,咱們將建立一個受權訪問服務,定義一個MVC客戶端,MVC客戶端經過IdentityServer上請求訪問令牌,並使用它來訪問API。

3.1 搭建 Authorization Server 服務

搭建認證受權服務

3.1.1 安裝Nuget包

IdentityServer4 程序包

3.1.2 配置內容

創建配置內容文件Config.cs

public static class Config
{
    public static IEnumerable<IdentityResource> IdentityResources =>
        new IdentityResource[]
    {
        new IdentityResources.OpenId(),
        new IdentityResources.Profile(),
    };

    public static IEnumerable<ApiScope> ApiScopes =>
        new ApiScope[]
    {
        new ApiScope("code_scope1")
    };

    public static IEnumerable<ApiResource> ApiResources =>
        new ApiResource[]
    {
        new ApiResource("api1","api1")
        {
            Scopes={ "code_scope1" },
            UserClaims={JwtClaimTypes.Role},  //添加Cliam 角色類型
            ApiSecrets={new Secret("apipwd".Sha256())}
        }
    };

    public static IEnumerable<Client> Clients =>
        new Client[]
    {
        new Client
        {
            ClientId = "code_client",
            ClientName = "code Auth",

            AllowedGrantTypes = GrantTypes.Code,

            RedirectUris ={
                "http://localhost:5002/signin-oidc", //跳轉登陸到的客戶端的地址
            },
            // RedirectUris = {"http://localhost:5002/auth.html" }, //跳轉登出到的客戶端的地址
            PostLogoutRedirectUris ={
                "http://localhost:5002/signout-callback-oidc",
            },
            ClientSecrets = { new Secret("511536EF-F270-4058-80CA-1C89C192F69A".Sha256()) },

            AllowedScopes = {
                IdentityServerConstants.StandardScopes.OpenId,
                IdentityServerConstants.StandardScopes.Profile,
                "code_scope1"
            },
            //容許將token經過瀏覽器傳遞
            AllowAccessTokensViaBrowser=true,
            // 是否須要贊成受權 (默認是false)
            RequireConsent=true
        }
    };
}

RedirectUris : 登陸成功回調處理的客戶端地址,處理回調返回的數據,能夠有多個。

PostLogoutRedirectUris :跳轉登出到的客戶端的地址。

這兩個都是配置的客戶端的地址,且是identityserver4組件裏面封裝好的地址,做用分別是登陸,註銷的回調

由於是受權碼受權的方式,因此咱們經過代碼的方式來建立幾個測試用戶。

新建測試用戶文件TestUsers.cs

public class TestUsers
    {
        public static List<TestUser> Users
        {
            get
            {
                var address = new
                {
                    street_address = "One Hacker Way",
                    locality = "Heidelberg",
                    postal_code = 69118,
                    country = "Germany"
                };

                return new List<TestUser>
                {
                    new TestUser
                    {
                        SubjectId = "1",
                        Username = "i3yuan",
                        Password = "123456",
                        Claims =
                        {
                            new Claim(JwtClaimTypes.Name, "i3yuan Smith"),
                            new Claim(JwtClaimTypes.GivenName, "i3yuan"),
                            new Claim(JwtClaimTypes.FamilyName, "Smith"),
                            new Claim(JwtClaimTypes.Email, "i3yuan@email.com"),
                            new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
                            new Claim(JwtClaimTypes.WebSite, "http://i3yuan.top"),
                            new Claim(JwtClaimTypes.Address, JsonSerializer.Serialize(address), IdentityServerConstants.ClaimValueTypes.Json)
                        }
                    }
                };
            }
        }
    }

返回一個TestUser的集合。

經過以上添加好配置和測試用戶後,咱們須要將用戶註冊到IdentityServer4服務中,接下來繼續介紹。

3.1.3 註冊服務

在startup.cs中ConfigureServices方法添加以下代碼:

public void ConfigureServices(IServiceCollection services)
        {
            var builder = services.AddIdentityServer()
               .AddTestUsers(TestUsers.Users); //添加測試用戶

            // in-memory, code config
            builder.AddInMemoryIdentityResources(Config.IdentityResources);
            builder.AddInMemoryApiScopes(Config.ApiScopes);
            builder.AddInMemoryApiResources(Config.ApiResources);
            builder.AddInMemoryClients(Config.Clients);

            // not recommended for production - you need to store your key material somewhere secure
            builder.AddDeveloperSigningCredential();
            services.ConfigureNonBreakingSameSiteCookies();
        }

3.1.4 配置管道

在startup.cs中Configure方法添加以下代碼:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseStaticFiles();
            app.UseRouting();
            app.UseCookiePolicy();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseIdentityServer();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
            }); 
        }

以上內容是快速搭建簡易IdentityServer項目服務的方式。

這搭建 Authorization Server 服務跟上一篇簡化模式有何不一樣之處呢?

  1. 在Config中配置客戶端(client)中定義了一個AllowedGrantTypes的屬性,這個屬性決定了Client能夠被哪一種模式被訪問,GrantTypes.Code受權碼模式。因此在本文中咱們須要添加一個Client用於支持受權碼模式(Authorization Code)。

3.2 搭建API資源

實現對API資源進行保護

3.2.1 快速搭建一個API項目

3.2.2 安裝Nuget包

IdentityServer4.AccessTokenValidation 包

3.2.3 註冊服務

在startup.cs中ConfigureServices方法添加以下代碼:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        services.AddAuthentication("Bearer")
          .AddIdentityServerAuthentication(options =>
          {
              options.Authority = "http://localhost:5001";
              options.RequireHttpsMetadata = false;
              options.ApiName = "api1";
              options.ApiSecret = "apipwd"; //對應ApiResources中的密鑰
          });
    }

AddAuthentication把Bearer配置成默認模式,將身份認證服務添加到DI中。

AddIdentityServerAuthentication把IdentityServer的access token添加到DI中,供身份認證服務使用。

3.2.4 配置管道

在startup.cs中Configure方法添加以下代碼:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }    
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
            });
        }

UseAuthentication將身份驗證中間件添加到管道中;

UseAuthorization 將啓動受權中間件添加到管道中,以便在每次調用主機時執行身份驗證受權功能。

3.2.5 添加API資源接口

[Route("api/[Controller]")]
[ApiController]
public class IdentityController:ControllerBase
{
    [HttpGet("getUserClaims")]
    [Authorize]
    public IActionResult GetUserClaims()
    {
        return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
    }
}

在IdentityController 控制器中添加 [Authorize] , 在進行請求資源的時候,需進行認證受權經過後,才能進行訪問。

3.3 搭建MVC 客戶端

實現對客戶端認證受權訪問資源

3.3.1 快速搭建一個MVC項目

3.3.2 安裝Nuget包

IdentityServer4.AccessTokenValidation 包

3.3.3 註冊服務

要將對 OpenID Connect 身份認證的支持添加到MVC應用程序中。

在startup.cs中ConfigureServices方法添加以下代碼:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
        services.AddAuthorization();

        services.AddAuthentication(options =>
            {
                options.DefaultScheme = "Cookies";
                options.DefaultChallengeScheme = "oidc";
            })
               .AddCookie("Cookies")  //使用Cookie做爲驗證用戶的首選方式
              .AddOpenIdConnect("oidc", options =>
              {
                  options.Authority = "http://localhost:5001";  //受權服務器地址
                  options.RequireHttpsMetadata = false;  //暫時不用https
                  options.ClientId = "code_client";
                  options.ClientSecret = "511536EF-F270-4058-80CA-1C89C192F69A";
                  options.ResponseType = "code"; //表明Authorization Code
                  options.Scope.Add("code_scope1"); //添加受權資源
                  options.SaveTokens = true; //表示把獲取的Token存到Cookie中
                  options.GetClaimsFromUserInfoEndpoint = true;
              });
         services.ConfigureNonBreakingSameSiteCookies();
    }
  1. AddAuthentication注入添加認證受權,當須要用戶登陸時,使用 cookie 來本地登陸用戶(經過「Cookies」做爲DefaultScheme),並將 DefaultChallengeScheme 設置爲「oidc」,

  2. 使用 AddCookie 添加能夠處理 cookie 的處理程序。

  3. AddOpenIdConnect用於配置執行 OpenID Connect 協議的處理程序和相關參數。Authority代表以前搭建的 IdentityServer 受權服務地址。而後咱們經過ClientIdClientSecret,識別這個客戶端。 SaveTokens用於保存從IdentityServer獲取的token至cookie,ture標識ASP.NETCore將會自動存儲身份認證session的access和refresh token。

3.3.4 配置管道

而後要確保認證服務執行對每一個請求的驗證,加入UseAuthenticationUseAuthorizationConfigure中,在startup.cs中Configure方法添加以下代碼:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();
            app.UseRouting();
            app.UseCookiePolicy();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }

UseAuthentication將身份驗證中間件添加到管道中;

UseAuthorization 將啓動受權中間件添加到管道中,以便在每次調用主機時執行身份驗證受權功能。

3.3.5 添加受權

在HomeController控制器並添加[Authorize]特性到其中一個方法。在進行請求的時候,需進行認證受權經過後,才能進行訪問。

[Authorize]
        public IActionResult Privacy()
        {
            ViewData["Message"] = "Secure page.";
            return View();
        }

還要修改主視圖以顯示用戶的Claim以及cookie屬性。

@using Microsoft.AspNetCore.Authentication

<h2>Claims</h2>

<dl>
    @foreach (var claim in User.Claims)
    {
        <dt>@claim.Type</dt>
        <dd>@claim.Value</dd>
    }
</dl>

<h2>Properties</h2>

<dl>
    @foreach (var prop in (await Context.AuthenticateAsync()).Properties.Items)
    {
        <dt>@prop.Key</dt>
        <dd>@prop.Value</dd>
    }
</dl>

訪問 Privacy 頁面,跳轉到認證服務地址,進行帳號密碼登陸,Logout 用於用戶的註銷操做。

3.3.6 添加資源訪問

HomeController控制器添加對API資源訪問的接口方法。在進行請求的時候,訪問API受保護資源。

/// <summary>
        /// 測試請求API資源(api1)
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> getApi()
        {
            var client = new HttpClient();
            var accessToken = await HttpContext.GetTokenAsync(OpenIdConnectParameterNames.AccessToken);
            if (string.IsNullOrEmpty(accessToken))
            {
                return Json(new { msg = "accesstoken 獲取失敗" });
            }
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            var httpResponse = await client.GetAsync("http://localhost:5003/api/identity/GetUserClaims"); 
            var result = await httpResponse.Content.ReadAsStringAsync();
            if (!httpResponse.IsSuccessStatusCode)
            {
                return Json(new { msg = "請求 api1 失敗。", error = result });
            }
            return Json(new
            {
                msg = "成功",
                data = JsonConvert.DeserializeObject(result)
            });
        }

測試這裏經過獲取accessToken以後,設置client請求頭的認證,訪問API資源受保護的地址,獲取資源。

3.4 效果

3.4.1 動圖

3.4.2 過程

在用戶訪問MVC程序時候,將用戶導向認證服務器,

在客戶端向受權服務器Authorization Endpoint進行驗證的時候,咱們能夠發現,向受權服務器發送的請求附帶的那些參數就是咱們以前說到的數據(clientid,redirect_url,type等)

繼續往下看,發如今用戶給予受權完成登陸以後,能夠看到在登陸後,受權服務器向重定向URL地址同時帶上一個受權碼數據帶給MVC程序。

隨後MVC向受權客戶端的Token終結點發送請求,從下圖能夠看到此次請求包含了client_id,client_secret,code,grant_type和redirect_uri,向受權服務器申請訪問令牌token, 而且在響應中能夠看到受權服務器覈對了受權碼和重定向地址URI,確認無誤後,向第三方應用發送訪問令牌(Access Token)和更新令牌(Refresh token)

完成獲取令牌後,訪問受保護資源的時候,帶上令牌請求訪問,能夠成功響應獲取用戶信息資源。

4、總結

  1. 本篇主要闡述以受權碼受權,編寫一個MVC客戶端,並經過客戶端以瀏覽器的形式請求IdentityServer上請求獲取訪問令牌,從而訪問受保護的API資源。
  2. 受權碼模式解決了簡化模式因爲token攜帶在url中,安全性方面不能保證問題,而經過受權碼的模式不直接返回token,而是先返回一個受權碼,而後再根據這個受權碼去請求token,這個請求token這個過程須要放在後臺,這種方式也更爲安全。適用於有後端的應用。
  3. 在後續會對這方面進行介紹繼續說明,數據庫持久化問題,以及如何應用在API資源服務器中和配置在客戶端中,會進一步說明。
  4. 若是有不對的或不理解的地方,但願你們能夠多多指正,提出問題,一塊兒討論,不斷學習,共同進步。
  5. 項目地址

5、附加

OpenID Connect資料

Authorization Code資料

samesite問題解決

相關文章
相關標籤/搜索