日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【One by One系列】IdentityServer4(四)授权码流程

發布時間:2023/12/4 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【One by One系列】IdentityServer4(四)授权码流程 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

接下來我們介紹新內容,OAuth2.0叫做授權碼(authorization code),在OpenID Connect中則屬于OpenId Connect Flow,稱為授權碼流程(Authorization Code Flow),這種方式主要場景:

  • 保密客戶端,服務器端的web應用

例如asp.net core mvc,這種由后端處理邏輯后,模板渲染的web框架

另外,這種方式主要是需要先去IdentityServer申請一個授權碼,然后再用授權碼獲取token。這種方式廣泛用于大廠的開放平臺,如微信、華為等等。

這種方式的安全性最高,因為它是server-server,即web應用的后端與IdentityServer交互通信,token都是存儲在后端。基本流程如下:

  • 1.請求IdentityServer的oauth/authorize? response_type=code&client_id=CLIENT_ID&redirect_uri=CALLBACK_URL&scope=read

redirect_uri為需要授權的應用的url

  • 2.callback?code=AUTHORIZATION_CODE

重定向至redirect_uri,且會在uri后增加授權碼

  • 3.后端請求oauth/token?client_id=CLIENT_ID&client_secret=CLIENT_SECRET& grant_type=authorization_code&code=AUTHORIZATION_CODE&redirect_uri=CALLBACK_URL

再攜帶code,去token端點,獲取token

在IdentityServer4中,大致也是這個流程,但是其中會有一些變化,為了安全,IdentityServer4是帶有PKCE支持的授權碼模式,后續我們會講到,先讓我們實踐一下,感受一下。

1.IdentityServer增加UI

上兩篇文章,主要針對的是客戶端憑證和密碼憑證,我們繼續在IdentityServer項目中進行增量開發。

1.1 增加MVC UI模板代碼

cd .\src\IdentityServer dotnet new is4ui

1.2 MVC生效

在依賴注入和管道中使mvc生效

  • Startup.ConfigureServices

//?uncomment,?if?you?want?to?add?an?MVC-based?UI services.AddControllersWithViews();
  • Startup.Configure

//?uncomment?if?you?want?to?add?MVC app.UseStaticFiles(); app.UseRouting();app.UseIdentityServer();//?uncomment,?if?you?want?to?add?MVC app.UseAuthorization(); app.UseEndpoints(endpoints?=> {endpoints.MapDefaultControllerRoute(); }); “

ps:is4inmem模板包含了基本的IdentityServer,同時也包含了標準UI界面(也就是上面添加的模板代碼)

1.3 修改launchSettings.json

{"profiles":?{"MVCClient":?{"commandName":?"Project","launchBrowser":?true,"applicationUrl":?"http://localhost:6002","environmentVariables":?{"ASPNETCORE_ENVIRONMENT":?"Development"}}} }

1.4 增加客戶端配置

new?Client{ClientId="mvc",ClientSecrets={?new?Secret("secret-mvc".Sha256())},AllowedGrantTypes?=?GrantTypes.Code,RequireConsent=true,//?where?to?redirect?to?after?loginRedirectUris?=?{?"http://localhost:6002/signin-oidc"?},//?where?to?redirect?to?after?logoutPostLogoutRedirectUris?=?{?"http://localhost:6002/signout-callback-oidc"?},AllowedScopes?=?new?List<string>{"api1",IdentityServerConstants.StandardScopes.OpenId,IdentityServerConstants.StandardScopes.Profile}}

2.創建新的asp.net core mvc客戶端

2.1 新建項目

cd .\src\ dotnet new mvc -n MVCClient dotnet sln add .\MVCClient\MVCClient.csproj

2.2 添加nuget引用

ASP.NET Core middleware that enables an application to support the OpenID Connect authentication workflow.

cd?.\MVCClient\ dotnet?add?package?Microsoft.AspNetCore.Authentication.OpenIdConnect

2.3 注冊OpenId Connect

using?System.IdentityModel.Tokens.Jwt;//?...JwtSecurityTokenHandler.DefaultMapInboundClaims?=?false;services.AddAuthentication(options?=>{options.DefaultScheme?=?"Cookies";options.DefaultChallengeScheme?=?"oidc";}).AddCookie("Cookies").AddOpenIdConnect("oidc",?options?=>{options.Authority?=?"http://localhost:5001";options.ClientId?=?"mvc";options.ClientSecret?=?"secret";options.ResponseType?=?"code";options.SaveTokens?=?true;//scopeoptions.Scope.Add("api1");});
  • AddAuthentication:添加身份認證服務

    • options.DefaultScheme=Cookies:我們使用cookie記錄本地登錄用戶

    • options.DefaultChallengeScheme=oidc:需要用戶登錄,將使用OpenID Connect協議

  • AddCookie:添加cookies的處理器

  • AddOpenIdConnect:配置執行OpenID Connect協議的處理器相關參數

    • options.Authority:標識所信賴的token服務地址

    • options.ClientId和options.ClientSecret:標識MVC客戶端

    • options.SaveTokens:保存從IdentityServer獲取的token至cookie,ture標識ASP.NETCore將會自動存儲身份認證session的access和refresh token

2.4 添加身份認證

?app.UseStaticFiles();app.UseRouting();app.UseAuthentication();app.UseAuthorization();app.UseEndpoints(endpoints?=>{endpoints.MapControllerRoute(name:?"default",pattern:?"{controller=Home}/{action=Index}/{id?}").RequireAuthorization();});

2.5 增加用戶退出

最后一步,是增加用戶退出操作。

對于像IdentityServer這樣的身份認證服務,清除本地應用程序cookie是不夠的。還需要往返于IdentityServer以清除中央單點登錄的session。

在控制器中增加退出操作代碼:

public?IActionResult?Logout() {return?SignOut("Cookies",?"oidc"); }

在視圖層_Layout.cshtml增加退出按鈕

?<div?class="navbar-collapse?collapse?d-sm-inline-flex?flex-sm-row-reverse"><ul?class="navbar-nav?flex-grow-1"><li?class="nav-item"><a?class="nav-link?text-dark"?asp-area=""?asp-controller="Home"?asp-action="Index">Home</a></li><li?class="nav-item"><a?class="nav-link?text-dark"?asp-area=""?asp-controller="Home"?asp-action="Privacy">Privacy</a></li><li?class="nav-item"><a?class="nav-link?text-dark"?asp-area=""?asp-controller="Home"?asp-action="Logout">LoginOut</a></li></ul></div>

2.6 修改Home/Index.cshtml

為了測試效果,修改小標題所示的視圖,讓其展示認證授權后的User.Claims

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

2.測試

啟動IdentityServer

cd .\IdentityServer\ dotnet run

用vs啟動MVCClient

  • 首先頁面進入MVCClient起始頁http://localhost:6002

  • 由于沒有登錄,將會跳轉至登錄頁http://localhost:5001/Account/Login

  • 鍵入正確的用戶名和密碼,又會重定向至http://localhost:6002

測試訪問api就不演示效果了,只給出相關代碼:

controller代碼:

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("https://localhost:6001/api/identity");ViewBag.Json?=?JArray.Parse(content).ToString();return?View("json"); }

總結

以上是生活随笔為你收集整理的【One by One系列】IdentityServer4(四)授权码流程的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。