前言
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();
搭建 Api Resource
建立一個用戶端工程項目,端口設定為5001
PM> Install-package IdentityServer4.AccessTokenValidation -version 2.7.0
在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);
}
app.UseIdentityServer();
測試
在用戶端values控制器上面增加[Authorize]
直接通路資源伺服器http://localhost:5001/api/values
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnL0kTMwADNwkTMx0COyEjNxADM5AzNykDM5EDMy0CO2ADO5ATMvwVOwkTMwIzLchjNwgTOwEzLcd2bsJ2Lc12bj5ycn9Gbi52YugTMwIzZtl2Lc9CX6MHc0RHaiojIsJye.png)
通路受限了 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.html