asp.net core IdentityServer4 實現 Client credentials(客戶端憑證)
前言
OAuth 2.0預設四種授權模式(GrantType)
- 授權碼模式(authorization_code)
- 簡化模式(implicit)
- 密碼模式(resource owner password credentials)
- 客戶端模式(client_credentials)
本章主要介紹客戶端模式(client credentials)
,他主要是由兩部分構成客戶端和認證伺服器.
認證伺服器在確定客戶端資訊無誤後向客戶端返回token,客戶端請求資源時帶著該token進行訪問.(在這種模式中使用者可直接向客戶端註冊,客戶端再以自己的名義請求認證伺服器)
搭建認證伺服器
建立一個Api專案工程,埠設定為5000
Package
PM> Install-package IdentityServer4 -version 2.5.3
建立一個類Config(配置要保護的資源和可以訪問該API的客戶端伺服器)
/// <summary> /// Identity配置 /// </summary> public class Config { /// <summary> /// 定義要保護的資源 /// </summary> /// <returns></returns> public static IEnumerable<ApiResource> GetApiResources() { return new List<ApiResource> { new ApiResource("api1", "My API") }; } /// <summary> /// 定義授權客戶端 /// </summary> /// <returns></returns> public static IEnumerable<Client> GetClients() { return new List<Client> { new Client() { ClientId = "client", AllowedGrantTypes = GrantTypes.ClientCredentials, //設定模式,客戶端模式 ClientSecrets = { new Secret("secret".Sha256()) }, AllowedScopes = { "api1" } } }; } }
配置Startup
在ConfigureServices方法中注入IdentityServer4服務
public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddIdentityServer()//IdentityServer4服務 .AddDeveloperSigningCredential() .AddInMemoryApiResources(Config.GetApiResources()) //配置資源 .AddInMemoryClients(Config.GetClients());//把配置檔案的Client配置資源放到記憶體 }
在Configure方法中新增IdentityServer4服務中介軟體
app.UseIdentityServer();
搭建Client
建立一個客戶端工程專案,埠設定為5001
Package
PM> Install-package IdentityServer4.AccessTokenValidation -version 2.7.0
配置Startup
在ConfigureServices新增認證伺服器地址
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:5000";//授權伺服器地址
options.RequireHttpsMetadata = false;//不需要https
options.ApiName = "api1";
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
在Configure方法中新增IdentityServer4服務中介軟體
app.UseIdentityServer();
測試
在客戶端values控制器上面增加[Authorize]
直接訪問資源伺服器http://localhost:5001/api/values
訪問受限了 code 401
啟動授權伺服器
http://localhost:5000/.well-known/openid-configuration
發現端點可通過/.well-known/openid-configuration
獲取token
啟動後我們通過token_endpoint獲取token
client_id為我們在授權伺服器配置的clientid,
client_secret為配置中的secret,
grant_type為授權模式此處為客戶端模式(client_credentials),
請求後返回憑證資訊,
我們通過access_token再去訪問資源伺服器
使用這種授權型別,會向token 。
code 200
概要
示例地址:https://github.com/fhcodegit/IdentityServer4.Samples
IdentityServer4敘述:https://www.cnblogs.com/yyfh/p/11590383.h