一、簡介
IdentityServer4 是用于 ASP.NET Core 的 OpenID Connect 和 OAuth 2.0 框架,通過中間件的方式集成,JWT(json web token)本身是一個格式,不是一個框架,在ids4中也用到了這種格式,而在很多公司的專案里(包括我們)使用JWT來完成鑒權機制,是在這個token格式的基礎上用代碼實作生成、頒發、校驗、重繪、過期等功能,這是IdentityServer4與JWT的區別,
二、配置
(1)新建一個空Api專案作為認證鑒權中心,Nuget安裝 IdentityServer4 包
(2)Startup Configure 啟用 ids4,ConfigureServices 配置 ApiResources資源、Clients客戶端、ApiScopes作用域 等等,呼叫新建的 InMemoryConfig 配置類


public class InMemoryConfig
{
public static IEnumerable<IdentityResource> IdentityResources =>
new IdentityResource[]
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
};
/// <summary>
/// ApiResource 資源串列
/// </summary>
public static IEnumerable<ApiResource> GetApiResources()
{
return new[]
{
new ApiResource("Users", "獲取用戶資訊API")
{
Scopes={ "scope1" }//必須
}
};
}
/// <summary>
/// ApiScopes 作用域
/// </summary>
public static IEnumerable<ApiScope> GetApiScopes()
{
return new ApiScope[]
{
new ApiScope("scope1")
};
}
/// <summary>
/// Client 客戶端
/// </summary>
public static IEnumerable<Client> GetClients()
{
return new[]
{
new Client
{
ClientId = "HomeJok.Authentication", //客戶端唯一標識
ClientName = "Authentication", //客戶端名稱
ClientSecrets = new [] { new Secret("wintersir".Sha256()) },//客戶端密碼,進行了加密
AllowedGrantTypes = GrantTypes.ClientCredentials, //授權方式,客戶端認證 ClientId+ClientSecrets
AllowedScopes = new [] { "scope1" }, //允許訪問的資源
Claims = new List<ClientClaim>(){
new ClientClaim(IdentityModel.JwtClaimTypes.Role,"Admin"),
new ClientClaim(IdentityModel.JwtClaimTypes.NickName,"WinterSir"),
new ClientClaim("email","[email protected]")
}
}
};
}
}
三、測驗 Token
以上就可以獲取到 token 了,啟動認證服務dotnet run urls=http://*:5000,用 Postman 測驗 token,在 jwt.io 里決議內容,


四、Api服務集成 ids4 認證
(1)上述操作完成了ids4認證服務,下面回到Api專案進行呼叫,Nuget安裝 IdentityServer4.AccessTokenValidation
(2)startup 配置 ids4 認證,在Api方法上啟用鑒權
(3)啟動Api服務dotnet run urls=http://*:8000用 Postman 獲取最新的 token,再呼叫 Api GetUserInfo

五、總結
可以看到,沒有添加 token 的請求回傳401無權限,在添加 token 后正常獲取用戶串列,這篇算是一個Demo,接下來還要學習常用的幾種授權模式、SSO、持久化等,
六、前人栽樹,后人乘涼
https://identityserver4.readthedocs.io/en/latest/index.html
https://www.cnblogs.com/cwsheng/p/13611036.html
https://www.cnblogs.com/stulzq/p/8119928.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/446960.html
標籤:.NET技术
