asp.net core系列 57 IS4 使用混合流(OIDC+OAuth2.0)添加API訪問


一.概述

  在上篇中,探討了交互式用戶身份驗證,使用的是OIDC協議。 在之前篇中對API訪問使用的是OAuth2.0協議。這篇把這兩個部分放在一起,OpenID Connect和OAuth 2.0組合的優點在於:可以使用單個協議和令牌服務,進行單次交換來實現這兩者。

  上篇中使用了OpenID Connect隱式流程。在隱式流程中,所有令牌都通過瀏覽器傳輸,這對於身份令牌來說是完全正確的。現在我們還想要一個訪問令牌。

  訪問令牌比身份令牌更敏感,如果不需要,我們不希望將它們暴露給“外部”世界。OpenID Connect包含一個名為“Hybrid”的流程,它為我們提供了兩全其美的優勢,身份令牌通過瀏覽器渠道傳輸,因此客戶端訪問API時先進行身份驗證。如果驗證成功,客戶端會打開令牌服務的反向通道以檢索訪問令牌。

  從Github中下載開源項目。該示例是在上篇示例的基礎之上,做的一點修改。涉及到三個項目:IdentityServer、Api、MvcClient。

 

二. IdentityServer 項目

  1.1 定義客戶端配置

    允許客戶端使用混合流Hybrid,添加一個客戶端密鑰ClientSecrets ,這將用於檢索反向通道上的訪問令牌。最后添加客戶端訪問offline_access范圍 -這允許請求刷新令牌來進行長時間的API訪問:

    public static IEnumerable<Client> GetClients()
        {
            return new List<Client>
            {
                new Client
                {
                    ClientId = "client",

                    // no interactive user, use the clientid/secret for authentication
                    AllowedGrantTypes = GrantTypes.ClientCredentials,

                    // secret for authentication
                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },

                    // scopes that client has access to
                    AllowedScopes = { "api1" }
                },
                // resource owner password grant client
                new Client
                {
                    ClientId = "ro.client",
                    AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,

                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },
                    AllowedScopes = { "api1" }
                },
                // OpenID Connect hybrid flow client (MVC)
                new Client
                {
                    ClientId = "mvc",
                    ClientName = "MVC Client",
                    //混合流
                    AllowedGrantTypes = GrantTypes.Hybrid,

                    //添加客戶端密鑰
                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },

                    RedirectUris           = { "http://localhost:5002/signin-oidc" },
                    PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },

                    AllowedScopes =
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        //api訪問范圍
                        "api1"
                    },
                    //刷新令牌來進行長時間的API訪問
                    AllowOfflineAccess = true
                }
            };
        }

  

三. API項目

  API項目沒有變動,可以考參上面的開源地址。也可以查看54篇。

 

四. MvcClient客戶端

  4.1 啟動類配置

    在啟動類Startup. ConfigureServices方法中,配置ClientSecret匹配IdentityServer的Secret。 添加offline_access和api1范圍。並設置ResponseType為code id_token,意味着“使用混合流”。 將website  聲明保留在我們的mvc客戶端標識中,需要使用ClaimActions顯示映射聲明。

       public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            services.AddAuthentication(options =>
                {
                    options.DefaultScheme = "Cookies";
                    options.DefaultChallengeScheme = "oidc";
                })
                .AddCookie("Cookies")
                .AddOpenIdConnect("oidc", options =>
                {
                    options.SignInScheme = "Cookies";

                    //若不設置Authority,就必須指定MetadataAddress
                    options.Authority = "http://localhost:5000";
                    options.RequireHttpsMetadata = false;

                    //客戶端標識ID
                    options.ClientId = "mvc";

                    //匹配IdentityServer的Secret
                    options.ClientSecret = "secret";

                    /*
                      ResponseType:OAuth 2.0響應類型值,一次請求中可以同時獲取Code和ID Token,使用的是混合流Hybrid Flow,
                      也可以使用OpenIdConnectResponseType枚舉。
                      code:授權代碼。當使用混合流時,總是返回這個值。
                      id_token:標識牌

                     下面是一個使用混合流響應示例:
                     HTTP / 1.1 302 Found
                     Location: https://client.example.org/cb#
                     code = SplxlOBeZQQYbYS6WxSbIA
                     & id_token = eyJ0...NiJ9.eyJ1c...I6IjIifX0.DeWt4Qu...ZXso
                     & state = af0ifjsldkj
                    */
                    options.ResponseType = "code id_token";

                    //是否將Tokens保存到AuthenticationProperties中,最終到瀏覽器cookie中
                    options.SaveTokens = true;

                    //是否從UserInfoEndpoint獲取Claims
                    options.GetClaimsFromUserInfoEndpoint = true;

                    //添加資源范圍,訪問api
                    options.Scope.Add("api1");
                    //離線訪問,此范圍值請求發出OAuth 2.0刷新令牌,該令牌可用於獲取訪問令牌,
                    //該令牌授予對最終用戶的UserInfo端點的訪問權,即使最終用戶不存在(未登錄)。
                    options.Scope.Add("offline_access");

                    //收集Claims
                    options.ClaimActions.MapJsonKey("website", "website");
                });
        }

    Configure方法配置不變。 

 

  4.2 使用訪問令牌

    在上面配置的OpenID Connect處理程序,會自動為我們保存令牌(在本案例中為identity身份,access 訪問和refresh 刷新)。這就是SaveTokens設置的作用。令牌存儲在cookie的properties部分中。訪問它們的最簡單方法是使用Microsoft.AspNetCore.Authentication命名空間中的擴展方法(GetTokenAsync)。

  //例如:
    var accessToken = await HttpContext.GetTokenAsync("access_token")
    var refreshToken = await HttpContext.GetTokenAsync("refresh_token");
    //下面方法Home/CallAPI調用受保護的API,先獲取訪問令牌,再使用訪問令牌調用API。
        public async Task<IActionResult> CallApi()
        {
            //獲取訪問令牌
            var accessToken = await HttpContext.GetTokenAsync("access_token");

            var client = new HttpClient();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            var content = await client.GetStringAsync("http://localhost:5001/identity");

            ViewBag.Json = JArray.Parse(content).ToString();
            return View("json");
        }

 

 五. 測試

  (1) 啟動IdentityServer程序http://localhost:5000

  (2) 啟動API程序http://localhost:5001。這二個程序屬於服務端

  (3) 啟動客戶端MvcClient程序http://localhost:5002

  (4) 用戶點擊Secure,開始握手授權,重定向到IdentityServer站點的登錄頁

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

            return View();
        }

  (5) 輸入用戶的用戶名和密碼,登錄成功。跳轉到IdentityServer站點consent同意頁面

    上面的應用程序訪問權限:MyAPI和Offline Access 是在客戶端程序中配置的:

        options.Scope.Add("api1");
        options.Scope.Add("offline_access");

  (6) 點擊 yes allow后,跳回到客戶端站點http://localhost:5002/Home/Secure,完成了交互式身份認證。

  (7) 調用http://localhost:5002/Home/CallAPI,獲取訪問令牌,請求受保護的api資源。調用CallAPI 時,是訪問的api站點http://localhost:5001/identity。

 

  參考文獻

    切換到混合流並添加API訪問

    OIDC使用混合流授權請求

 


免責聲明!

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



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