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

一.概述

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

  上篇中使用了OpenID Connect隱式流程。在隱式流程中,全部令牌都經過瀏覽器傳輸,這對於身份令牌來講是徹底正確的。如今咱們還想要一個訪問令牌。git

  訪問令牌比身份令牌更敏感,若是不須要,咱們不但願將它們暴露給「外部」世界。OpenID Connect包含一個名爲「Hybrid」的流程,它爲咱們提供了一箭雙鵰的優點,身份令牌經過瀏覽器渠道傳輸,所以客戶端訪問API時先進行身份驗證。若是驗證成功,客戶端會打開令牌服務的反向通道以檢索訪問令牌。github

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

 

二. IdentityServer 項目

  1.1 定義客戶端配置json

    容許客戶端使用混合流Hybrid,添加一個客戶端密鑰ClientSecrets ,這將用於檢索反向通道上的訪問令牌。最後添加客戶端訪問offline_access範圍 -這容許請求刷新令牌來進行長時間的API訪問: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 啓動類配置cookie

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

       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方法配置不變。 async

 

  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使用混合流受權請求

相關文章
相關標籤/搜索