天天看點

第十節:IdentityServer4隐式模式介紹和代碼實操演練

一. 前言

1.簡介

  簡化模式(implicit grant type)不通過第三方應用程式的伺服器,直接在浏覽器中向認證伺服器申請令牌,步驟在浏覽器中完成,令牌對通路者是可見的,且用戶端不需要認證。

注:該模式也有很大的弊端,就是請求令牌在浏覽器中能被看到。

2. 流程圖

第十節:IdentityServer4隐式模式介紹和代碼實操演練

流程

(A)用戶端将使用者導向認證伺服器。

(B)使用者決定是否給于用戶端授權。

(C)假設使用者給予授權,認證伺服器将使用者導向用戶端指定的"重定向URI",并在URI的Hash部分包含了通路令牌。

(D)浏覽器向資源伺服器送出請求,其中不包括上一步收到的Hash值(#号的部分)。

(E)資源伺服器傳回一個網頁,其中包含的代碼可以擷取Hash值中的令牌。

(F)浏覽器執行上一步獲得的腳本,提取出令牌。

(G)浏覽器将令牌發給用戶端。

(H)用戶端拿到令牌以後,就可以去請求資源伺服器擷取資源了。

3. 流程剖析

步驟A:導向認證伺服器,如下請求,進而再導向認證伺服器的登入頁面。

GET /authorize?response_type=token&client_id=s6BhdRkqt3&state=xyz&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb            

參數包括:

  response_type:表示授權類型,此處的值固定為"token",必選項。

  client_id:表示用戶端的ID,必選項。

  redirect_uri:表示重定向的URI,可選項。

  scope:表示權限範圍,可選項。

  state:表示用戶端的目前狀态,可以指定任意值,認證伺服器會原封不動地傳回這個值。

步驟C:伺服器回應用戶端的URI

Location  http://example.com/cb#access_token=2YotnFZFEjr1zCsicMWpAA&state=xyz&token_type=example&expires_in=3600           

  access_token:表示通路令牌,必選項。

  token_type:表示令牌類型,該值大小寫不敏感,必選項。

  expires_in:表示過期時間,機關為秒。如果省略該參數,必須其他方式設定過期時間。

  scope:表示權限範圍,如果與用戶端申請的範圍一緻,此項可省略。

  state:如果用戶端的請求中包含這個參數,認證伺服器的回應也必須一模一樣包含這個參數。

步驟D:浏覽器會通路Location指定的網址,但是Hash部分(#後的部分)不會發送

步驟E:服務提供商的資源伺服器發送過來的代碼,會提取出Hash中的令牌。

二. 代碼實操

1. 項目準備

 (1). ID4_Server2:授權認證伺服器 【位址:http://127.0.0.1:7070】

 (2). MvcImplictClient2:web性質的用戶端 【位址:http://127.0.0.1:7071】

2. 搭建步驟

(一). ID4_Server2

 (1).通過Nuget安裝【IdentityServer4 4.0.2】程式集

 (2).內建IDS4官方的UI頁面

  進入ID4_Server2的根目錄,cdm模式下依次輸入下面指令,內建IDS4相關的UI頁面,發現新增或改變了【Quickstart】【Views】【wwwroot】三個檔案夾

  A.【dotnet new -i identityserver4.templates】

  B.【dotnet new is4ui --force】 其中--force代表覆寫的意思, 空項目可以直接輸入:【dotnet new is4ui】,不需要覆寫。

PS. 有時候正值版本更新期間,上述指令下載下傳下來的檔案可能不是最新的,這個時候隻需要手動去下載下傳,然後把上述三個檔案夾copy到項目裡即可

(下載下傳位址:https://github.com/IdentityServer/IdentityServer4.Quickstart.UI)

第十節:IdentityServer4隐式模式介紹和代碼實操演練

 (3).建立Config1配置類,進行可以使用IDS4資源的配置

  A.隐式模式: AllowedGrantTypes = GrantTypes.Implicit,

  B.授權成功傳回的位址:RedirectUris = { "http://127.0.0.1:7071/signin-oidc" }, 7071是MvcImplictClient2用戶端的端口,signin-oidc是IDS4監聽的一個位址,可以拿到token資訊。

代碼分享:

第十節:IdentityServer4隐式模式介紹和代碼實操演練
第十節:IdentityServer4隐式模式介紹和代碼實操演練
public class Config1
    {
        /// <summary>
        /// IDS資源
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<IdentityResource> GetIds()
        {
            return new List<IdentityResource>
            {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile(),
            };
        }

        /// <summary>
        /// 可以使用ID4 Server 用戶端資源
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<Client> GetClients()
        {
            List<Client> clients = new List<Client>() {
                new Client
                {
                    ClientId = "client1",
                    ClientSecrets = { new Secret("123456".Sha256()) },
                    //隐式模式
                    AllowedGrantTypes = GrantTypes.Implicit,
                    //需要确認授權
                    RequireConsent = true,
                    RequirePkce = true,
                    //允許token通過浏覽器
                    AllowAccessTokensViaBrowser=true,               
                    // where to redirect to after login(登入)
                    RedirectUris = { "http://127.0.0.1:7071/signin-oidc" },
                    // where to redirect to after logout(退出)
                    PostLogoutRedirectUris = { "http://127.0.0.1:7071/signout-callback-oidc" },
                    //允許的範圍
                    AllowedScopes = new List<string>
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile
                    },
                    AlwaysIncludeUserClaimsInIdToken=true
                }
            };
            return clients;
        }

        /// <summary>
        /// 定義可以使用ID4的使用者資源
        /// </summary>
        /// <returns></returns>
        public static List<TestUser> GetUsers()
        {
            var address = new
            {
                street_address = "One Hacker Way",
                locality = "Heidelberg",
                postal_code = 69118,
                country = "Germany"
            };
            return new List<TestUser>()
            {
                new TestUser
                {
                        SubjectId = "001",
                        Username = "ypf1",    //賬号
                        Password = "123456",  //密碼
                        Claims =
                        {
                            new Claim(JwtClaimTypes.Name, "Alice Smith"),
                            new Claim(JwtClaimTypes.GivenName, "Alice"),
                            new Claim(JwtClaimTypes.FamilyName, "Smith"),
                            new Claim(JwtClaimTypes.Email, "[email protected]"),
                            new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
                            new Claim(JwtClaimTypes.WebSite, "http://alice.com"),
                            new Claim(JwtClaimTypes.Address, JsonSerializer.Serialize(address), IdentityServerConstants.ClaimValueTypes.Json)
                        }
                 },
                 new TestUser
                 {
                        SubjectId = "002",
                        Username = "ypf2",
                        Password = "123456",
                        Claims =
                        {
                            new Claim(JwtClaimTypes.Name, "Bob Smith"),
                            new Claim(JwtClaimTypes.GivenName, "Bob"),
                            new Claim(JwtClaimTypes.FamilyName, "Smith"),
                            new Claim(JwtClaimTypes.Email, "[email protected]"),
                            new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
                            new Claim(JwtClaimTypes.WebSite, "http://bob.com"),
                            //這是新的序列化模式哦
                            new Claim(JwtClaimTypes.Address, JsonSerializer.Serialize(address), IdentityServerConstants.ClaimValueTypes.Json)
                        }
                  }
            };
        }
    }      

View Code

 (4).在Startup類中注冊、啟用、修改路由

  A.在ConfigureService中進行IDS4的注冊.

  B.在Configure中啟用IDS4 app.UseIdentityServer();

  C.路由,這裡需要注意,不要和原Controllers裡沖突即可,該項目中沒有Controllers檔案夾,不要特别配置。

第十節:IdentityServer4隐式模式介紹和代碼實操演練
第十節:IdentityServer4隐式模式介紹和代碼實操演練
public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();

            //注冊IDS4資訊(簡化模式)
            services.AddIdentityServer()
                    .AddDeveloperSigningCredential()
                    .AddInMemoryIdentityResources(Config1.GetIds())
                    .AddInMemoryClients(Config1.GetClients())
                    .AddTestUsers(Config1.GetUsers());
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();
            app.UseRouting();

            //啟用IDS4
            app.UseIdentityServer();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");

                //修改預設啟動路由
                //endpoints.MapDefaultControllerRoute();
            });
        }
    }      

 (5).配置啟動端口,直接設定預設值: webBuilder.UseStartup<Startup>().UseUrls("http://127.0.0.1:7070");

 (6).修改屬性友善調試:項目屬性→ 調試→應用URL(p),改為:http://127.0.0.1:7070 (把IISExpress和控制台啟動的方式都改了,友善調試)

第十節:IdentityServer4隐式模式介紹和代碼實操演練

(二). MvcImplictClient2

 (1).通過Nuget安裝【Microsoft.AspNetCore.Authentication.OpenIdConnect 3.1.5】程式集

 (2).在Startup中進行配置

  a. ConfigureSevice:添加Cookie認證、添加通過OIDC協定遠端請求認證(注意的幾個地方:Authority、ResponseType、ResponseMode)

  b. Config:開啟認證、開啟授權、預設路由後面添加授權RequireAuthorization。

第十節:IdentityServer4隐式模式介紹和代碼實操演練
第十節:IdentityServer4隐式模式介紹和代碼實操演練
public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();


            JwtSecurityTokenHandler.DefaultMapInboundClaims = false;   
            //添加Cookie認證
            services.AddAuthentication(options =>
            {
                options.DefaultScheme = "Cookies";
                options.DefaultChallengeScheme = "oidc";
            })
            .AddCookie("Cookies")
            //通過OIDC協定遠端請求認證
            .AddOpenIdConnect("oidc", options =>
            {
                options.Authority = "http://127.0.0.1:7070";   //認證授權伺服器位址
                options.RequireHttpsMetadata = false;
                options.ClientId = "client1";    //用戶端ID
                options.ClientSecret = "123456"; //用戶端秘鑰
                options.ResponseType = OpenIdConnectResponseType.IdTokenToken;  //請求類型
                options.ResponseMode = OpenIdConnectResponseMode.FormPost;      //請求方式
                options.SaveTokens = true;
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();

            app.UseRouting();
            //開啟認證
            app.UseAuthentication();
            //開啟授權
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                //修改預設路由, RequireAuthorization
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}").RequireAuthorization();

            });
        }
    }      

 (3).編寫控制器和view頁面中的内容

控制器代碼:

public IActionResult Index()
   {
       string accessToken = HttpContext.GetTokenAsync("access_token").Result;
       string idToken = HttpContext.GetTokenAsync("id_token").Result;
       var claimsList = from c in User.Claims select new { c.Type, c.Value };
       return View();
    }
   public IActionResult Logout()
   {
       return SignOut("Cookies", "oidc");
   }      

View頁面代碼:

第十節:IdentityServer4隐式模式介紹和代碼實操演練
第十節:IdentityServer4隐式模式介紹和代碼實操演練
@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>      

 (4).配置啟動端口,直接設定預設值: webBuilder.UseStartup<Startup>().UseUrls("http://127.0.0.1:7071");

 (5).修改屬性友善調試:項目屬性→ 調試→應用URL(p),改為:http://127.0.0.1:7071(把IISExpress和控制台啟動的方式都改了,友善調試)

第十節:IdentityServer4隐式模式介紹和代碼實操演練

3. 剖析測試

(1). 啟動ID4_Server2項目

第十節:IdentityServer4隐式模式介紹和代碼實操演練

(2). 啟動MvcImplictClient2項目

第十節:IdentityServer4隐式模式介紹和代碼實操演練
第十節:IdentityServer4隐式模式介紹和代碼實操演練
第十節:IdentityServer4隐式模式介紹和代碼實操演練

用Fiddler檢測上述過程

第十節:IdentityServer4隐式模式介紹和代碼實操演練

參考文檔:https://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html

!

  • 作       者 : Yaopengfei(姚鵬飛)
  • 部落格位址 : http://www.cnblogs.com/yaopengfei/
  • 聲     明1 : 如有錯誤,歡迎讨論,請勿謾罵^_^。
  • 聲     明2 : 原創部落格請在轉載時保留原文連結或在文章開頭加上本人部落格位址,否則保留追究法律責任的權利。