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


一. 前言

1.簡介

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

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

2. 流程圖

 

流程

(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)

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

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

  B.授權成功返回的地址:RedirectUris = { "http://127.0.0.1:7071/signin-oidc" }, 7071是MvcImplictClient2客戶端的端口,signin-oidc是IDS4監聽的一個地址,可以拿到token信息。

代碼分享:

    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, "AliceSmith@email.com"),
                            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, "BobSmith@email.com"),
                            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文件夾,不要特別配置。

代碼分享:

  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();
            });
        }
    }
View Code

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

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

(二). MvcImplictClient2

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

 (2).在Startup中進行配置

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

  b. Config:開啟認證、開啟授權、默認路由后面添加授權RequireAuthorization

代碼分享:

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();

            });
        }
    }
View Code

 (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頁面代碼:

@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>
View Code

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

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

 

3. 剖析測試

(1). 啟動ID4_Server2項目

(2). 啟動MvcImplictClient2項目

 

 

用Fiddler檢測上述過程

 

 

 

 

 

 

 

 

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

 

 

!

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM