一.前言
本文已經更新到 .NET Core 2.2
OAuth 2.0 資源所有者密碼模式允許客戶端向令牌服務發送用戶名和密碼,並獲取代表該用戶的訪問令牌。
除了通過無法瀏覽器進行交互的應用程序之外,通常建議不要使用資源所有者密碼模式。 一般來說,當您要對用戶進行身份驗證並請求訪問令牌時,使用其中一個交互式 OpenID Connect 流程通常要好得多。
在這里使用這種模式是為了學習如何快速在 IdentityServer 中使用它,
二.添加用戶
就像API資源(也稱為 Scope)、客戶端一樣,用戶也有一個基於內存存儲(In-Memory)的實現。
有關如何正確存儲(持久化存儲)和管理用戶帳戶的詳細信息,請查看基於 ASP.NET Identity的快速入門。
TestUser
類代表測試用戶及其身份信息單元(Claim)。 讓我們通過在 config
類中添加以下代碼來創建幾個用戶:
首先添加以下語句 到Config.cs
文件中:
using IdentityServer4.Test;
public static List<TestUser> GetUsers()
{
return new List<TestUser>
{
new TestUser
{
SubjectId = "1",
Username = "alice",
Password = "password"
},
new TestUser
{
SubjectId = "2",
Username = "bob",
Password = "password"
}
};
}
然后將測試用戶注冊到 IdentityServer:
public void ConfigureServices(IServiceCollection services)
{
// configure identity server with in-memory stores, keys, clients and scopes
services.AddIdentityServer()
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients())
.AddTestUsers(Config.GetUsers());
}
AddTestUsers
方法幫我們做了以下幾件事:
- 為資源所有者密碼授權添加支持
- 添加對用戶相關服務的支持,這服務通常為登錄 UI 所使用(我們將在下一個快速入門中用到登錄 UI)
- 為基於測試用戶的身份信息服務添加支持(你將在下一個快速入門中學習更多與之相關的東西)
四.為資源所有者密碼授權添加一個客戶端定義
你可以通過修改 ·AllowedGrantTypes· 屬性簡單地添加對已有客戶端授權類型的支持。
通常你會想要為資源所有者用例創建獨立的客戶端,添加以下代碼到你配置中的客戶端定義中:
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
// other clients omitted...
// resource owner password grant client
new Client
{
ClientId = "ro.client",
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = { "api1" }
}
};
}
使用密碼授權請求一個令牌
創建一個 ResourceOwnerPassword 控制台項目,通過Nuget添加 IdentityModel
包
通過如下代碼獲取Token
// request token
var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
{
Address = disco.TokenEndpoint,
ClientId = "ro.client",
ClientSecret = "secret",
UserName = "alice",
Password = "password",
Scope = "api1"
});
if (tokenResponse.IsError)
{
Console.WriteLine(tokenResponse.Error);
return;
}
Console.WriteLine(tokenResponse.Json);
當您將令牌發送到身份API終結點時,您會注意到與客戶端模式相比有一個小但重要的區別。 訪問令牌現在將包含唯一標識用戶的sub
claim。 通過在調用API之后檢查內容變量可以看到這個“sub”,並且控制器應用程序也會在屏幕上顯示該claim。
sub claim的存在(或不存在)允許API區分代表客戶端的調用和代表用戶的調用。
下面這張圖,是理解的客戶端請求流程,
關於上圖的補充說明,這里講一下。api資源收到第一個請求之后,會去id4服務器公鑰,然后用公鑰驗證token是否合法,如果合法進行后面后面的有效性驗證。有且只有第一個請求才會去id4服務器請求公鑰,后面的請求都會用第一次請求的公鑰來驗證,這也是jwt去中心化驗證的思想。
五.使用Postman調試
使用postman調用生成token接口需要配置如下參數:
最后github地址:https://github.com/stulzq/IdentityServer4.Samples/tree/master/Quickstarts/2_ResourceOwnerPasswords 如果你覺得對你有用,歡迎star