一、簡介
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","641187567@qq.com")
}
}
};
}
}
三、測試 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