一、前言
從上一篇關于客戶端憑證模式中,我們通過創建一個認證授權訪問服務,定義一個API和要訪問它的客戶端,客戶端通過IdentityServer上請求訪問令牌,并使用它來控制訪問API,其中,我們也注意到了在4.x版本中于之前3.x版本之間存在的差異,
所以在這一篇中,我們將通過多種授權模式中的資源所有者密碼憑證授權模式進行說明,主要針對介紹IdentityServer保護API的資源,資源密碼憑證授權訪問API資源,
二、初識
如果你高度信任某個應用Client,也允許用戶把用戶名和密碼,直接告訴該應用Client,該應用Client就使用你的密碼,申請令牌,這種方式稱為"密碼式"(password),
這種模式適用于鑒權服務器與資源服務器是高度相互信任的,例如兩個服務都是同個團隊或者同一公司開發的,
2.1 適用范圍
資源所有者密碼憑證授權模式,適用于當資源所有者與客戶端具有良好信任關系的場景,比如客戶端是設備的作業系統或具備高權限的應用,授權服務器在開放此種授權模式時必須格外小心,并且只有在別的模式不可用時才允許這種模式,
這種模式下,應用client可能存了用戶密碼這不安全性問題,所以才需要高可信的應用,
主要適用于用來做遺留專案升級為oauth2的適配授權使用,當然如果client是自家的應用,也是可以的,同時支持refresh token,
例如,A站點 需要添加了 OAuth 2.0 作為對其現有基礎架構的一個授權機制,對于現有的客戶端轉變為這種授權方案,資源所有者密碼憑據授權將是最方便的,因為他們只需使用現有的帳戶詳細資訊(比如用戶名和密碼)來獲取訪問令牌,
2.2 密碼授權流程:
+----------+
| Resource |
| Owner |
| |
+----------+
v
| Resource Owner
(A) Password Credentials
|
v
+---------+ +---------------+
| |>--(B)---- Resource Owner ------->| |
| | Password Credentials | Authorization |
| Client | | Server |
| |<--(C)---- Access Token ---------<| |
| | (w/ Optional Refresh Token) | |
+---------+ +---------------+
資源所有者密碼憑證授權流程描述
(A)資源所有者向客戶端提供其用戶名和密碼,
(B)客戶端從授權中請求訪問令牌服務器的令牌端點,以獲取訪問令牌,當發起該請求時,授權服務器需要認證客戶端的身份,
(C) 授權服務器驗證客戶端身份,同時也驗證資源所有者的憑據,如果都通過,則簽發訪問令牌,
2.2.1 程序詳解
訪問令牌請求
| 引數 | 是否必須 | 含義 |
|---|---|---|
| grant_type | 必需 | 授權型別,值固定為“password”, |
| username | 必需 | 用戶名 |
| password | 必需 | 密碼 |
| scope | 可選 | 表示授權范圍, |
同時將允許其他請求引數client_id和client_secret,或在HTTP Basic auth標頭中接受客戶端ID和密鑰,
驗證用戶名密碼
示例:
客戶端身份驗證兩種方式
1、Authorization: Bearer base64(resourcesServer:123)
2、client_id(客戶端標識),client_secret(客戶端秘鑰),username(用戶名),password(密碼),
(用戶的操作:輸入賬號和密碼)
A 網站要求用戶提供 B 網站的用戶名和密碼,拿到以后,A 就直接向 B 請求令牌,
POST /oauth/token HTTP/1.1
Host: authorization-server.com
grant_type=password
&[email protected]
&password=1234luggage
&client_id=xxxxxxxxxx
&client_secret=xxxxxxxxxx
上面URL中,grant_type引數是授權方式,這里的password是“密碼式”,username和password是B的用戶名和密碼,
2.2.2 訪問令牌回應
第二步,B 網站驗證身份通過后,直接給出令牌,注意,這時不需要跳轉,而是把令牌放在 JSON 資料里面,作為 HTTP 回應,A 因此拿到令牌,
回應給用戶令牌資訊(access_token),如下所示
{
"access_token": "訪問令牌",
"token_type": "Bearer",
"expires_in": 4200,
"scope": "server",
"refresh_token": "重繪令牌"
}
用戶使用這個令牌訪問資源服務器,當令牌失效時使用重繪令牌去換取新的令牌,
這種方式需要用戶給出自己的用戶名/密碼,顯然風險很大,因此只適用于其他授權方式都無法采用的情況,而且必須是用戶高度信任的應用,
三、實踐
在示例實踐中,我們將創建一個授權訪問服務,定義一個API和要訪問它的客戶端,客戶端通過IdentityServer上請求訪問令牌,并使用它來訪問API,
3.1 搭建 Authorization Server 服務
搭建認證授權服務
3.1.1 安裝Nuget包
IdentityServer4程式包
3.1.2 配置內容
建立配置內容檔案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" }
},
};
}
因為是資源所有者密碼憑證授權的方式,所以我們通過代碼的方式來創建幾個測驗用戶,
新建測驗用戶檔案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, "[email protected]"),
new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
new Claim(JwtClaimTypes.WebSite, "http://i3yuan.top"),
new Claim(JwtClaimTypes.Address, JsonSerializer.Serialize(address), IdentityServerConstants.ClaimValueTypes.Json)
}
}
};
}
}
}
回傳一個TestUser的集合,
通過以上添加好配置和測驗用戶后,我們需要將用戶注冊到IdentityServer4服務中,接下來繼續介紹,
3.1.3 注冊服務
在startup.cs中ConfigureServices方法添加如下代碼:
public void ConfigureServices(IServiceCollection services)
{
var builder = services.AddIdentityServer()
.AddTestUsers(TestUsers.Users); //添加測驗用戶
// in-memory, code config
builder.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 secure
builder.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!");
});
});
}
以上內容是快速搭建簡易IdentityServer專案服務的方式,
這搭建 Authorization Server 服務跟上一篇客戶端憑證模式有何不同之處呢?
- 在Config中配置客戶端(client)中定義了一個
AllowedGrantTypes的屬性,這個屬性決定了Client可以被哪種模式被訪問,GrantTypes.ClientCredentials為客戶端憑證模式,GrantTypes.ResourceOwnerPassword為資源所有者密碼憑證授權,所以在本文中我們需要添加一個Client用于支持資源所有者密碼憑證模式(ResourceOwnerPassword),- 因為資源所有者密碼憑證模式需要用到用戶名和密碼所以要添加用戶,而客戶端憑證模式不需要,這也是兩者的不同之處,
3.2 搭建API資源
實作對API資源進行保護
3.2.1 快速搭建一個API專案
3.2.2 安裝Nuget包
IdentityServer4.AccessTokenValidation 包
3.2.3 注冊服務
在startup.cs中ConfigureServices方法添加如下代碼:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddAuthorization();
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:5001";
options.RequireHttpsMetadata = https://www.cnblogs.com/i3yuan/archive/2020/11/02/false;
options.ApiName ="api1";
options.ApiSecret = "apipwd"; //對應ApiResources中的密鑰
});
}
AddAuthentication把Bearer配置成默認模式,將身份認證服務添加到DI中,
AddIdentityServerAuthentication把IdentityServer的access token添加到DI中,供身份認證服務使用,
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將身份驗證中間件添加到管道中;
UseAuthorization 將啟動授權中間件添加到管道中,以便在每次呼叫主機時執行身份驗證授權功能,
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] , 在進行請求資源的時候,需進行認證授權通過后,才能進行訪問,
這搭建API資源跟上一篇客戶端憑證模式有何不同之處呢?
我們可以發現這跟上一篇基本相似,但是可能需要注意的地方應該是
ApiName和ApiSecret,要跟你配置的API資源名稱和API資源密鑰相同,
3.3 搭建Client客戶端
實作對API資源的訪問和獲取資源
3.3.1 搭建一個表單程式
3.3.2 安裝Nuget包
IdentityModel 包
3.3.3 獲取令牌
客戶端與授權服務器進行身份驗證并向令牌端點請求訪問令牌,授權服務器對客戶端進行身份驗證,如果有效,頒發訪問令牌,
IdentityModel 包括用于發現 IdentityServer 各個終結點(EndPoint)的客戶端庫,
我們可以使用從 IdentityServer 元資料獲取到的Token終結點請求令牌:
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;
}
//請求token
tokenResponse = 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 呼叫API
要將Token發送到API,通常使用HTTP Authorization標頭, 這是使用
SetBearerToken擴展方法完成,
private void getApi_Click(object sender, EventArgs e)
{
//呼叫認證api
if (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多了兩個引數,一個用戶名,一個密碼
- 請求Token中使用
IdentityModel包的方法RequestPasswordTokenAsync,實作用戶密碼方式獲取令牌,
以上展示的代碼有不明白的,可以看本篇專案原始碼,專案地址為 :資源所有者密碼憑證模式
3.4 效果
3.4.1 專案測驗

3.4.2 postman測驗

四、拓展
從上一篇的客戶端憑證模式到這一篇的資源所有者資源密碼憑證模式,我們都已經初步掌握了大致的授權流程,以及專案搭建獲取訪問受保護的資源,但是我們也可能發現了,如果是僅僅為了訪問保護的API資源的話,加不加用戶和密碼好像也沒什么區別呢,
但是如果仔細對比兩種模式在獲取token,以及訪問api回傳的資料可以發現,資源所有者密碼憑證模式回傳的Claim的數量資訊要多一些,但是客戶端模式回傳的明顯少了一些,這是因為客戶端不涉及用戶資訊,所以資源密碼憑證模式
可以根據用戶資訊做具體的資源權限判斷,
比如,在TestUser有一個Claims屬性,允許自已添加Claim,有一個ClaimTypes列舉列出了可以直接添加的Claim,所以我們可以為用戶設定角色,來判斷角色的權限功能,做簡單的權限管理,
4.1 添加用戶角色
在之前創建的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, "[email protected]"),
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
因為要用到ApiResources,ApiResources的建構式有一個多載支持傳進一個Claim集合,用于允許該Api資源可以攜帶那些Claim, 所以在專案下的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驗證
在API資源專案中,修改下被保護Api的,使其支持Role驗證,
[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 效果
可以看到,為我們添加了一個Role Claim,效果如下:

五、總結
- 本篇主要闡述以資源所有者密碼憑證授權,撰寫一個客戶端,以及受保護的資源,并通過客戶端請求IdentityServer上請求獲取訪問令牌,從而獲取受保護的資源,
- 這種模式主要使用client_id和client_secret以及用戶名密碼通過應用Client(客戶端)直接獲取秘鑰,但是存在client可能存了用戶密碼這不安全性問題,如果client是自家高可信的應用,也是可以使用的,同時如果遺留專案升級為oauth2的授權機制也是適配適用的,
- 在后續會對其中的其他授權模式,資料庫持久化問題,以及如何應用在API資源服務器中和配置在客戶端中,會進一步說明,
- 如果有不對的或不理解的地方,希望大家可以多多指正,提出問題,一起討論,不斷學習,共同進步,
- 專案地址
六、附加
Resource Owner Password Validation資料
Password Grant資料
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/199330.html
標籤:.NET技术
上一篇:C# 類的成員
