IdentityServer4系列 | 资源密码凭证模式
一、前言
從上一篇關(guān)于客戶端憑證模式中,我們通過創(chuàng)建一個(gè)認(rèn)證授權(quán)訪問服務(wù),定義一個(gè)API和要訪問它的客戶端,客戶端通過IdentityServer上請求訪問令牌,并使用它來控制訪問API。其中,我們也注意到了在4.x版本中于之前3.x版本之間存在的差異。
所以在這一篇中,我們將通過多種授權(quán)模式中的資源所有者密碼憑證授權(quán)模式進(jìn)行說明,主要針對介紹IdentityServer保護(hù)API的資源,資源密碼憑證授權(quán)訪問API資源。
二、初識(shí)
如果你高度信任某個(gè)應(yīng)用Client,也允許用戶把用戶名和密碼,直接告訴該應(yīng)用Client。該應(yīng)用Client就使用你的密碼,申請令牌,這種方式稱為"密碼式"(password)。
這種模式適用于鑒權(quán)服務(wù)器與資源服務(wù)器是高度相互信任的,例如兩個(gè)服務(wù)都是同個(gè)團(tuán)隊(duì)或者同一公司開發(fā)的。
2.1 適用范圍
資源所有者密碼憑證授權(quán)模式,適用于當(dāng)資源所有者與客戶端具有良好信任關(guān)系的場景,比如客戶端是設(shè)備的操作系統(tǒng)或具備高權(quán)限的應(yīng)用。授權(quán)服務(wù)器在開放此種授權(quán)模式時(shí)必須格外小心,并且只有在別的模式不可用時(shí)才允許這種模式。
這種模式下,應(yīng)用client可能存了用戶密碼這不安全性問題,所以才需要高可信的應(yīng)用。
主要適用于用來做遺留項(xiàng)目升級為oauth2的適配授權(quán)使用,當(dāng)然如果client是自家的應(yīng)用,也是可以的,同時(shí)支持refresh token。
例如,A站點(diǎn) 需要添加了 OAuth 2.0 作為對其現(xiàn)有基礎(chǔ)架構(gòu)的一個(gè)授權(quán)機(jī)制。對于現(xiàn)有的客戶端轉(zhuǎn)變?yōu)檫@種授權(quán)方案,資源所有者密碼憑據(jù)授權(quán)將是最方便的,因?yàn)樗麄冎恍枋褂矛F(xiàn)有的帳戶詳細(xì)信息(比如用戶名和密碼)來獲取訪問令牌。
2.2 密碼授權(quán)流程:
?????+----------+|?Resource?||??Owner???||??????????|+----------+v|????Resource?Owner(A)?Password?Credentials|v+---------+??????????????????????????????????+---------------+|?????????|>--(B)----?Resource?Owner?------->|???????????????||?????????|?????????Password?Credentials?????|?Authorization?||?Client??|??????????????????????????????????|?????Server????||?????????|<--(C)----?Access?Token?---------<|???????????????||?????????|????(w/?Optional?Refresh?Token)???|???????????????|+---------+??????????????????????????????????+---------------+資源所有者密碼憑證授權(quán)流程描述
(A)資源所有者向客戶端提供其用戶名和密碼。
(B)客戶端從授權(quán)中請求訪問令牌服務(wù)器的令牌端點(diǎn),以獲取訪問令牌。當(dāng)發(fā)起該請求時(shí),授權(quán)服務(wù)器需要認(rèn)證客戶端的身份。
(C) 授權(quán)服務(wù)器驗(yàn)證客戶端身份,同時(shí)也驗(yàn)證資源所有者的憑據(jù),如果都通過,則簽發(fā)訪問令牌。
2.2.1 過程詳解
訪問令牌請求
| grant_type | 必需 | 授權(quán)類型,值固定為“password”。 |
| username | 必需 | 用戶名 |
| password | 必需 | 密碼 |
| scope | 可選 | 表示授權(quán)范圍。 |
同時(shí)將允許其他請求參數(shù)client_id和client_secret,或在HTTP Basic auth標(biāo)頭中接受客戶端ID和密鑰。
驗(yàn)證用戶名密碼
示例:客戶端身份驗(yàn)證兩種方式
1、Authorization: Bearer base64(resourcesServer:123)?
2、client_id(客戶端標(biāo)識(shí)),client_secret(客戶端秘鑰),username(用戶名),password(密碼)。
(用戶的操作:輸入賬號和密碼)
A 網(wǎng)站要求用戶提供 B 網(wǎng)站的用戶名和密碼。拿到以后,A 就直接向 B 請求令牌。
POST?/oauth/token?HTTP/1.1 Host:?authorization-server.comgrant_type=password &username=user@example.com &password=1234luggage &client_id=xxxxxxxxxx &client_secret=xxxxxxxxxx上面URL中,grant_type參數(shù)是授權(quán)方式,這里的password是“密碼式”,username和password是B的用戶名和密碼。
2.2.2 訪問令牌響應(yīng)
第二步,B 網(wǎng)站驗(yàn)證身份通過后,直接給出令牌。注意,這時(shí)不需要跳轉(zhuǎn),而是把令牌放在 JSON 數(shù)據(jù)里面,作為 HTTP 回應(yīng),A 因此拿到令牌。
響應(yīng)給用戶令牌信息(access_token),如下所示
{"access_token":?"訪問令牌","token_type":?"Bearer","expires_in":?4200,"scope":?"server","refresh_token":?"刷新令牌" }用戶使用這個(gè)令牌訪問資源服務(wù)器,當(dāng)令牌失效時(shí)使用刷新令牌去換取新的令牌。
這種方式需要用戶給出自己的用戶名/密碼,顯然風(fēng)險(xiǎn)很大,因此只適用于其他授權(quán)方式都無法采用的情況,而且必須是用戶高度信任的應(yīng)用。
三、實(shí)踐
在示例實(shí)踐中,我們將創(chuàng)建一個(gè)授權(quán)訪問服務(wù),定義一個(gè)API和要訪問它的客戶端,客戶端通過IdentityServer上請求訪問令牌,并使用它來訪問API。
3.1 搭建 Authorization Server 服務(wù)
搭建認(rèn)證授權(quán)服務(wù)
3.1.1 安裝Nuget包
IdentityServer4?程序包
3.1.2 配置內(nèi)容
建立配置內(nèi)容文件Config.cs
????public?static?class?Config{public?static?IEnumerable<IdentityResource>?IdentityResources?=>new?IdentityResource[]{new?IdentityResources.OpenId(),new?IdentityResources.Profile(),};public?static?IEnumerable<ApiScope>?ApiScopes?=>new?ApiScope[]{new?ApiScope("password_scope1")};public?static?IEnumerable<ApiResource>?ApiResources?=>new?ApiResource[]{new?ApiResource("api1","api1"){Scopes={?"password_scope1"?},ApiSecrets={new?Secret("apipwd".Sha256())}??//api密鑰}};public?static?IEnumerable<Client>?Clients?=>new?Client[]{new?Client{ClientId?=?"password_client",ClientName?=?"Resource?Owner?Password",AllowedGrantTypes?=?GrantTypes.ResourceOwnerPassword,ClientSecrets?=?{?new?Secret("511536EF-F270-4058-80CA-1C89C192F69A".Sha256())?},AllowedScopes?=?{?"password_scope1"?}},};}因?yàn)槭?strong>資源所有者密碼憑證授權(quán)的方式,所以我們通過代碼的方式來創(chuàng)建幾個(gè)測試用戶。
新建測試用戶文件TestUsers.cs
????public?class?TestUsers{public?static?List<TestUser>?Users{get{var?address?=?new{street_address?=?"One?Hacker?Way",locality?=?"Heidelberg",postal_code?=?69118,country?=?"Germany"};return?new?List<TestUser>{new?TestUser{SubjectId?=?"1",Username?=?"i3yuan",Password?=?"123456",Claims?={new?Claim(JwtClaimTypes.Name,?"i3yuan?Smith"),new?Claim(JwtClaimTypes.GivenName,?"i3yuan"),new?Claim(JwtClaimTypes.FamilyName,?"Smith"),new?Claim(JwtClaimTypes.Email,?"i3yuan@email.com"),new?Claim(JwtClaimTypes.EmailVerified,?"true",?ClaimValueTypes.Boolean),new?Claim(JwtClaimTypes.WebSite,?"http://i3yuan.top"),new?Claim(JwtClaimTypes.Address,?JsonSerializer.Serialize(address),?IdentityServerConstants.ClaimValueTypes.Json)}}};}}}返回一個(gè)TestUser的集合。
通過以上添加好配置和測試用戶后,我們需要將用戶注冊到IdentityServer4服務(wù)中,接下來繼續(xù)介紹。
3.1.3 注冊服務(wù)
在startup.cs中ConfigureServices方法添加如下代碼:
????????public?void?ConfigureServices(IServiceCollection?services){var?builder?=?services.AddIdentityServer().AddTestUsers(TestUsers.Users);?//添加測試用戶//?in-memory,?code?configbuilder.AddInMemoryIdentityResources(Config.IdentityResources);builder.AddInMemoryApiScopes(Config.ApiScopes);builder.AddInMemoryApiResources(Config.ApiResources);builder.AddInMemoryClients(Config.Clients);//?not?recommended?for?production?-?you?need?to?store?your?key?material?somewhere?securebuilder.AddDeveloperSigningCredential();}3.1.4 配置管道
在startup.cs中Configure方法添加如下代碼:
????????public?void?Configure(IApplicationBuilder?app,?IWebHostEnvironment?env){if?(env.IsDevelopment()){app.UseDeveloperExceptionPage();}app.UseRouting();app.UseIdentityServer();app.UseEndpoints(endpoints?=>{endpoints.MapGet("/",?async?context?=>{await?context.Response.WriteAsync("Hello?World!");});});}以上內(nèi)容是快速搭建簡易IdentityServer項(xiàng)目服務(wù)的方式。
這搭建 Authorization Server 服務(wù)跟上一篇客戶端憑證模式有何不同之處呢?
在Config中配置客戶端(client)中定義了一個(gè)AllowedGrantTypes的屬性,這個(gè)屬性決定了Client可以被哪種模式被訪問,GrantTypes.ClientCredentials為客戶端憑證模式,GrantTypes.ResourceOwnerPassword為資源所有者密碼憑證授權(quán)。所以在本文中我們需要添加一個(gè)Client用于支持資源所有者密碼憑證授權(quán)模式(ResourceOwnerPassword)。
因?yàn)?strong>資源所有者密碼憑證授權(quán)需要用到用戶名和密碼所以要添加用戶,而客戶端憑證模式不需要,這也是兩者的不同之處。
3.2 搭建API資源
實(shí)現(xiàn)對API資源進(jìn)行保護(hù)
3.2.1 快速搭建一個(gè)API項(xiàng)目
3.2.2 安裝Nuget包
IdentityServer4.AccessTokenValidation 包
3.2.3 注冊服務(wù)
在startup.cs中ConfigureServices方法添加如下代碼:
????public?void?ConfigureServices(IServiceCollection?services){services.AddControllersWithViews();services.AddAuthorization();services.AddAuthentication("Bearer").AddIdentityServerAuthentication(options?=>{options.Authority?=?"http://localhost:5001";options.RequireHttpsMetadata?=?false;options.ApiName?=?"api1";options.ApiSecret?=?"apipwd";?//對應(yīng)ApiResources中的密鑰});}AddAuthentication把Bearer配置成默認(rèn)模式,將身份認(rèn)證服務(wù)添加到DI中。
AddIdentityServerAuthentication把IdentityServer的access token添加到DI中,供身份認(rèn)證服務(wù)使用。
3.2.4 配置管道
在startup.cs中Configure方法添加如下代碼:
????????public?void?Configure(IApplicationBuilder?app,?IWebHostEnvironment?env){if?(env.IsDevelopment()){app.UseDeveloperExceptionPage();}????app.UseRouting();app.UseAuthentication();app.UseAuthorization();app.UseEndpoints(endpoints?=>{endpoints.MapDefaultControllerRoute();});}UseAuthentication將身份驗(yàn)證中間件添加到管道中;
UseAuthorization 將啟動(dòng)授權(quán)中間件添加到管道中,以便在每次調(diào)用主機(jī)時(shí)執(zhí)行身份驗(yàn)證授權(quán)功能。
3.2.5 添加API資源接口
[Route("api/[Controller]")] [ApiController] public?class?IdentityController:ControllerBase {[HttpGet("getUserClaims")][Authorize]public?IActionResult?GetUserClaims(){return?new?JsonResult(from?c?in?User.Claims?select?new?{?c.Type,?c.Value?});} }在IdentityController 控制器中添加 [Authorize] , 在進(jìn)行請求資源的時(shí)候,需進(jìn)行認(rèn)證授權(quán)通過后,才能進(jìn)行訪問。
這搭建API資源跟上一篇客戶端憑證模式有何不同之處呢?
我們可以發(fā)現(xiàn)這跟上一篇基本相似,但是可能需要注意的地方應(yīng)該是ApiName和ApiSecret,要跟你配置的API資源名稱和API資源密鑰相同。
3.3 搭建Client客戶端
實(shí)現(xiàn)對API資源的訪問和獲取資源
3.3.1 搭建一個(gè)窗體程序
3.3.2 安裝Nuget包
IdentityModel?包
3.3.3 獲取令牌
客戶端與授權(quán)服務(wù)器進(jìn)行身份驗(yàn)證并向令牌端點(diǎn)請求訪問令牌。授權(quán)服務(wù)器對客戶端進(jìn)行身份驗(yàn)證,如果有效,頒發(fā)訪問令牌。
IdentityModel?包括用于發(fā)現(xiàn)?IdentityServer?各個(gè)終結(jié)點(diǎn)(EndPoint)的客戶端庫。
我們可以使用從?IdentityServer?元數(shù)據(jù)獲取到的Token終結(jié)點(diǎn)請求令牌:
????????private?void?getToken_Click(object?sender,?EventArgs?e){var?client?=?new?HttpClient();var?disco?=?client.GetDiscoveryDocumentAsync(this.txtIdentityServer.Text).Result;if?(disco.IsError){this.tokenList.Text?=?disco.Error;return;}//請求tokentokenResponse?=?client.RequestPasswordTokenAsync(new?PasswordTokenRequest{Address?=?disco.TokenEndpoint,ClientId?=this.txtClientId.Text,ClientSecret?=?this.txtClientSecret.Text,Scope?=?this.txtApiScopes.Text,UserName=this.txtUserName.Text,Password=this.txtPassword.Text}).Result;if?(tokenResponse.IsError){this.tokenList.Text?=?disco.Error;return;}this.tokenList.Text?=?JsonConvert.SerializeObject(tokenResponse.Json);this.txtToken.Text?=?tokenResponse.AccessToken;}3.3.4 調(diào)用API
要將Token發(fā)送到API,通常使用HTTP Authorization標(biāo)頭。這是使用SetBearerToken擴(kuò)展方法完成。
????????private?void?getApi_Click(object?sender,?EventArgs?e){//調(diào)用認(rèn)證apiif?(string.IsNullOrEmpty(txtToken.Text)){MessageBox.Show("token值不能為空");return;}var?apiClient?=?new?HttpClient();//apiClient.SetBearerToken(tokenResponse.AccessToken);apiClient.SetBearerToken(this.txtToken.Text);var?response?=?apiClient.GetAsync(this.txtApi.Text).Result;if?(!response.IsSuccessStatusCode){this.resourceList.Text?=?response.StatusCode.ToString();}else{this.resourceList.Text?=?response.Content.ReadAsStringAsync().Result;}}這搭建Client客戶端跟上一篇客戶端憑證模式有何不同之處呢?
客戶端請求token多了兩個(gè)參數(shù),一個(gè)用戶名,一個(gè)密碼
請求Token中使用IdentityModel包的方法RequestPasswordTokenAsync,實(shí)現(xiàn)用戶密碼方式獲取令牌。
以上展示的代碼有不明白的,可以看本篇項(xiàng)目源碼,項(xiàng)目地址為 :資源所有者密碼憑證模式
https://github.com/i3yuan/Yuan.IdentityServer4.Demo/tree/main/DiffAuthMode/ResourceOwnerPasswords
3.4 效果
3.4.1 項(xiàng)目測試
3.4.2 postman測試
四、拓展
從上一篇的客戶端憑證模式到這一篇的資源所有者資源密碼憑證模式,我們都已經(jīng)初步掌握了大致的授權(quán)流程,以及項(xiàng)目搭建獲取訪問受保護(hù)的資源,但是我們也可能發(fā)現(xiàn)了,如果是僅僅為了訪問保護(hù)的API資源的話,加不加用戶和密碼好像也沒什么區(qū)別呢。
但是如果仔細(xì)對比兩種模式在獲取token,以及訪問api返回的數(shù)據(jù)可以發(fā)現(xiàn),資源所有者密碼憑證模式返回的Claim的數(shù)量信息要多一些,但是客戶端模式返回的明顯少了一些,這是因?yàn)榭蛻舳瞬簧婕坝脩粜畔ⅰK再Y源密碼憑證模式可以根據(jù)用戶信息做具體的資源權(quán)限判斷。
比如,在TestUser有一個(gè)Claims屬性,允許自已添加Claim,有一個(gè)ClaimTypes枚舉列出了可以直接添加的Claim。所以我們可以為用戶設(shè)置角色,來判斷角色的權(quán)限功能,做簡單的權(quán)限管理。
4.1 添加用戶角色
在之前創(chuàng)建的TestUsers.cs文件的User方法中,添加Cliam的角色熟悉,如下:
public?class?TestUsers {public?static?List<TestUser>?Users{get{var?address?=?new{street_address?=?"One?Hacker?Way",locality?=?"Heidelberg",postal_code?=?69118,country?=?"Germany"};return?new?List<TestUser>{new?TestUser{SubjectId?=?"1",Username?=?"i3yuan",Password?=?"123456",Claims?={new?Claim(JwtClaimTypes.Name,?"i3yuan?Smith"),new?Claim(JwtClaimTypes.GivenName,?"i3yuan"),new?Claim(JwtClaimTypes.FamilyName,?"Smith"),new?Claim(JwtClaimTypes.Email,?"i3yuan@email.com"),new?Claim(JwtClaimTypes.EmailVerified,?"true",?ClaimValueTypes.Boolean),new?Claim(JwtClaimTypes.WebSite,?"http://i3yuan.top"),new?Claim(JwtClaimTypes.Address,?JsonSerializer.Serialize(address),?IdentityServerConstants.ClaimValueTypes.Json),new?Claim(JwtClaimTypes.Role,"admin")??//添加角色},}};}} }4.2 配置API資源需要的Cliam
因?yàn)橐玫紸piResources,ApiResources的構(gòu)造函數(shù)有一個(gè)重載支持傳進(jìn)一個(gè)Claim集合,用于允許該Api資源可以攜帶那些Claim, 所以在項(xiàng)目下的Config類的ApiResources做出如下修改:
????????public?static?IEnumerable<ApiResource>?ApiResources?=>new?ApiResource[]{new?ApiResource("api1","api1"){Scopes={?"password_scope1"?},UserClaims={JwtClaimTypes.Role},??//添加Cliam?角色類型ApiSecrets={new?Secret("apipwd".Sha256())}}};4.3 添加支持Role驗(yàn)證
在API資源項(xiàng)目中,修改下被保護(hù)Api的,使其支持Role驗(yàn)證。
????[HttpGet("getUserClaims")]//[Authorize][Authorize(Roles?="admin")]public?IActionResult?GetUserClaims(){return?new?JsonResult(from?c?in?User.Claims?select?new?{?c.Type,?c.Value?});}4.4 效果
可以看到,為我們添加了一個(gè)Role Claim,效果如下:
五、總結(jié)
本篇主要闡述以資源所有者密碼憑證授權(quán),編寫一個(gè)客戶端,以及受保護(hù)的資源,并通過客戶端請求IdentityServer上請求獲取訪問令牌,從而獲取受保護(hù)的資源。
這種模式主要使用client_id和client_secret以及用戶名密碼通過應(yīng)用Client(客戶端)直接獲取秘鑰,但是存在client可能存了用戶密碼這不安全性問題,如果client是自家高可信的應(yīng)用,也是可以使用的,同時(shí)如果遺留項(xiàng)目升級為oauth2的授權(quán)機(jī)制也是適配適用的。
在后續(xù)會(huì)對其中的其他授權(quán)模式,數(shù)據(jù)庫持久化問題,以及如何應(yīng)用在API資源服務(wù)器中和配置在客戶端中,會(huì)進(jìn)一步說明。
如果有不對的或不理解的地方,希望大家可以多多指正,提出問題,一起討論,不斷學(xué)習(xí),共同進(jìn)步。
項(xiàng)目地址
https://github.com/i3yuan/Yuan.IdentityServer4.Demo/tree/main/DiffAuthMode/ResourceOwnerPasswords
六、附加
Resource Owner Password Validation資料
Password Grant資料
總結(jié)
以上是生活随笔為你收集整理的IdentityServer4系列 | 资源密码凭证模式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C# 中的 in 参数和性能分析
- 下一篇: 深入探究ASP.NET Core Sta