IdentityServer4 (5) 混合模式(Hybrid)


寫在前面

1、源碼(.Net Core 2.2)

  git地址:https://github.com/yizhaoxian/CoreIdentityServer4Demo.git

2、相關章節

  2.1、《IdentityServer4 (1) 客戶端授權模式(Client Credentials)
  2.2、《IdentityServer4 (2) 密碼授權(Resource Owner Password)
  2.3、《IdentityServer4 (3) 授權碼模式(Authorization Code)
  2.4、《IdentityServer4 (4) 靜默刷新(Implicit)
  2.5、《IdentityServer4 (5) 混合模式(Hybrid)

3、參考資料

  IdentityServer4 中文文檔 http://www.identityserver.com.cn/
  IdentityServer4 英文文檔 https://identityserver4.readthedocs.io/en/latest/
  OpenID Connect 官網 https://openid.net/connect/
  OpenID Connect 中文 https://www.cnblogs.com/linianhui/p/openid-connect-core.html
  OpenID Connect和OAuth 2.0對比:https://www.jianshu.com/p/d453076e6433
  Oauth 2.0 官網:https://oauth.net/2/
  Oauth 2.0 授權框架:https://tools.ietf.org/html/rfc6749#section-4.2.1

一、服務端

1、定義客戶端

    new Client{
        ClientId="mvc client Hybrid", //客戶端Id
        ClientName="測試客戶端 Hybrid", //客戶端名稱 隨便寫 
        ClientSecrets={ new Secret("mvc secret Hybrid".Sha256()) },

        AllowedGrantTypes=GrantTypes.Hybrid,//驗證模式 

        // 如果客戶端 response_type 包含 token 這里必須啟用
        //AllowAccessTokensViaBrowser=true,

        RedirectUris = { "http://localhost:5003/signin-oidc" },  
        //注銷重定向的url
        PostLogoutRedirectUris = { "http://localhost:5003/signout-callback-oidc" },

        AllowOfflineAccess=true,
        AlwaysIncludeUserClaimsInIdToken=true,
          
        //客戶端訪問權限
        AllowedScopes =
        {
            "api1",
            IdentityServerConstants.StandardScopes.OpenId,
            IdentityServerConstants.StandardScopes.Email,
            IdentityServerConstants.StandardScopes.Address,
            IdentityServerConstants.StandardScopes.Phone,
            IdentityServerConstants.StandardScopes.Profile,
            "roles",
        }

二、客戶端

1、修改StartUp.cs

ConfigureServices()

//關閉了 JWT 身份信息類型映射
//這樣就允許 well-known 身份信息(比如,“sub” 和 “idp”)無干擾地流過。
//這個身份信息類型映射的“清理”必須在調用 AddAuthentication()之前完成
//區別可參考下面截圖,
//簡單理解 
//jwt 的 key 映射出來是 http://xxxxxxxxxxxxxxx
//well-known 映射出來是 sub idp 這樣簡潔的字符
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
//添加認證信息
services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
options =>
{
    options.AccessDeniedPath = "/Authorization/NoPermission";
})
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
 {
     //IdentityServer4 服務器地址
     options.Authority = "http://localhost:5002";
     options.ClientId = "mvc client Hybrid";
     options.ClientSecret = "mvc secret Hybrid";
     options.RequireHttpsMetadata = false;
     options.SaveTokens = true;
     options.ResponseType = OidcConstants.ResponseTypes.CodeIdToken;

     //如果請求token 就必須再定義客戶端的時候設置運行通過瀏覽器來返回AccessToken
     //options.ResponseType = OidcConstants.ResponseTypes.CodeToken;
     //options.ResponseType = OidcConstants.ResponseTypes.CodeIdTokenToken;

     options.Scope.Clear();
     options.Scope.Add("api1");
     options.Scope.Add(OidcConstants.StandardScopes.OpenId);
     options.Scope.Add(OidcConstants.StandardScopes.Email);
     options.Scope.Add(OidcConstants.StandardScopes.Phone);
     options.Scope.Add(OidcConstants.StandardScopes.Address);
     options.Scope.Add(OidcConstants.StandardScopes.Profile);
     options.Scope.Add(OidcConstants.StandardScopes.OfflineAccess);
     options.Scope.Add("roles"); 

     //去掉默認過濾的 claim,這樣 User.Claims 里就會出現這個 claim
     options.ClaimActions.Remove("nbf");

     //增加過濾的 claim,這樣 User.Claims 里就會刪除這個 claim
     options.ClaimActions.DeleteClaim("sid");

     options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
     {
         //映射 User.Name
         NameClaimType = JwtClaimTypes.Name,
         RoleClaimType = JwtClaimTypes.Role
     };
 });

Configure()

   app.UseStaticFiles();
   //寫在 UseMvc() 前面
   app.UseAuthentication();
   app.UseMvcWithDefaultRoute();

三、API資源

  參考之前的文章《IdentityServer4 (1) 客戶端授權模式》

四、測試

1、點擊受保護的資源

2、跳轉到授權服務器並登陸

3、點擊同意,自動跳轉回原來的頁面

 

4、測試訪問 api1 資源

  點擊上圖按鈕 測試api1

 


免責聲明!

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



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