一. 前言
1.簡介
授權碼模式(authorization code)是功能最完整、流程最嚴密的授權模式。它的特點就是通過客戶端的后台服務器,與"服務提供商"的認證服務器進行互動。
2. 流程圖
流程
(A)用戶訪問客戶端,后者將前者導向認證服務器。
(B)用戶選擇是否給予客戶端授權。
(C)假設用戶給予授權,認證服務器將用戶導向客戶端事先指定的"重定向URI"(redirection URI),同時附上一個授權碼。
(D)客戶端收到授權碼,附上早先的"重定向URI",向認證服務器申請令牌。這一步是在客戶端的后台的服務器上完成的,對用戶不可見。
(E)認證服務器核對了授權碼和重定向URI,確認無誤后,向客戶端發送訪問令牌(access token)和更新令牌(refresh token)。
(F) 拿到令牌后,可以盡情的請求資源服務器了。
3. 流程剖析
步驟A:導向認證服務器,如下請求,進而再導向認證服務器的登錄頁面。
GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb Host: server.example.com
參數包括:
response_type:表示授權類型,此處的值固定為"code",必選項。
client_id:表示客戶端的ID,必選項。
redirect_uri:表示重定向的URI,可選項。
scope:表示權限范圍,可選項。
state:表示客戶端的當前狀態,可以指定任意值,認證服務器會原封不動地返回這個值。
步驟C:服務器回應客戶端的URI
Location
https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA
&state=xyz
參數包括:
code:表示授權碼,必選項。該碼的有效期應該很短,通常設為10分鍾,客戶端只能使用該碼一次,否則會被授權服務器拒絕。該碼與客戶端ID和重定向URI,是一一對應關系。
state:如果客戶端的請求中包含這個參數,認證服務器的回應也必須一模一樣包含這個參數。
步驟D:客戶端攜帶授權碼code像認證服務器申請令牌,這一步一般是封裝代碼實現,看不到具體代碼。
Content-Type: application/x-www-form-urlencoded POST /authorize?grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb
參數包括:
grant_type:表示使用的授權模式,必選項,此處的值固定為"authorization_code"。
code:表示上一步獲得的授權碼,必選項。
redirect_uri:表示重定向URI,必選項,且必須與A步驟中的該參數值保持一致。
client_id:表示客戶端ID,必選項。
步驟E:認證服務器返回令牌等信息。
{ "access_token":"2YotnFZFEjr1zCsicMWpAA", "token_type":"example", "expires_in":3600, "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA", "example_parameter":"example_value" }
參數包括:
access_token:表示訪問令牌,必選項。
token_type:表示令牌類型,該值大小寫不敏感,必選項,可以是bearer類型或mac類型。
expires_in:表示過期時間,單位為秒。如果省略該參數,必須其他方式設置過期時間。
refresh_token:表示更新令牌,用來獲取下一次的訪問令牌,可選項。
scope:表示權限范圍,如果與客戶端申請的范圍一致,此項可省略。
二. 代碼實操演練
1. 項目准備
(1). ID4_Server2:授權認證服務器 【地址:http://127.0.0.1:7070】
(2). MvcCodeClient2:web性質的客戶端 【地址:http://127.0.0.1:7072】
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).創建Config2配置類,進行可以使用IDS4資源的配置
A.授權碼模式: AllowedGrantTypes = GrantTypes.Code,
B.授權成功返回的地址:RedirectUris = { "http://127.0.0.1:7072/signin-oidc" }, 7072是MvcCodeClient2客戶端的端口,signin-oidc是IDS4監聽的一個地址,可以拿到token信息。
代碼分享:

public class Config2 { /// <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.Code, //需要確認授權 RequireConsent = true, RequirePkce = true, //允許token通過瀏覽器 AllowAccessTokensViaBrowser=true, // where to redirect to after login(登錄) RedirectUris = { "http://127.0.0.1:7072/signin-oidc" }, // where to redirect to after logout(退出) PostLogoutRedirectUris = { "http://127.0.0.1:7072/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) } } }; }
(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(Config2.GetIds()) .AddInMemoryClients(Config2.GetClients()) .AddTestUsers(Config2.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(); }); } }
(5).配置啟動端口,直接設置默認值: webBuilder.UseStartup<Startup>().UseUrls("http://127.0.0.1:7070");
(6).修改屬性方便調試:項目屬性→ 調試→應用URL(p),改為:http://127.0.0.1:7070 (把IISExpress和控制台啟動的方式都改了,方便調試)
(二). MvcCodeClient2
(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.Code; options.ResponseMode = OpenIdConnectResponseMode.Query; 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(); }); } }
(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>
(4).配置啟動端口,直接設置默認值: webBuilder.UseStartup<Startup>().UseUrls("http://127.0.0.1:7072");
(5).修改屬性方便調試:項目屬性→ 調試→應用URL(p),改為:http://127.0.0.1:7072 (把IISExpress和控制台啟動的方式都改了,方便調試)
3. 剖析測試
(1). 啟動ID4_Server2項目
(2). 啟動MvcCodeClient2項目
用Fiddler檢測上述過程,進行剖析:
(1). 導向IDS4認證頁面的的參數
(2). 重定向到IDS4登錄頁面的參數
(3).授權頁面傳遞的參數
(4). 返回客戶端sign-oidc鏈接,附帶授權碼code
(5). 客戶端攜帶授權碼等信息請求認證服務,認證通過,返回token信息
參考文檔:https://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html
!
- 作 者 : Yaopengfei(姚鵬飛)
- 博客地址 : http://www.cnblogs.com/yaopengfei/
- 聲 明1 : 如有錯誤,歡迎討論,請勿謾罵^_^。
- 聲 明2 : 原創博客請在轉載時保留原文鏈接或在文章開頭加上本人博客地址,否則保留追究法律責任的權利。