IdentityServer 預設以 "JWT" (JSON Web令牌)格式發出訪問令牌。 今天的每個相關平臺都支持驗證JWT令牌, "這裡" 可以找到一個很好的JWT庫列表。熱門庫例如: ASP.NET Core的 "JWT bearer authentication handler" Kata ...
IdentityServer 預設以JWT(JSON Web令牌)格式發出訪問令牌。
今天的每個相關平臺都支持驗證JWT令牌,這裡可以找到一個很好的JWT庫列表。熱門庫例如:
- ASP.NET Core的JWT bearer authentication handler
- Katana的JWT bearer authentication middleware
- Katana的IdentityServer authentication middleware
- NodeJS的jsonwebtoken
保護基於ASP.NET Core的API只需在DI中配置JWT承載認證處理程式,並將認證中間件添加到管道:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
// base-address of your identityserver
options.Authority = "https://demo.identityserver.io";
// name of the API resource
options.Audience = "api1";
});
}
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
app.UseAuthentication();
app.UseMvc();
}
}
29.1 IdentityServer身份驗證處理程式
我們的身份驗證處理程式與上述處理程式的用途相同(實際上它在內部使用Microsoft JWT庫),但添加了一些其他功能:
- 支持JWT和參考令牌
- 用於引用標記的可擴展緩存
- 統一配置模型
- 範圍驗證
對於最簡單的情況,我們的處理程式配置看起來非常類似於上面的代碼段:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
// base-address of your identityserver
options.Authority = "https://demo.identityserver.io";
// name of the API resource
options.ApiName = "api1";
});
}
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
app.UseAuthentication();
app.UseMvc();
}
}
29.2 支持引用標記
如果傳入令牌不是JWT,我們的中間件將聯繫發現文檔中的內省端點以驗證令牌。由於內省端點需要身份驗證,因此您需要提供已配置的API密鑰,例如:
.AddIdentityServerAuthentication(options =>
{
// base-address of your identityserver
options.Authority = "https://demo.identityserver.io";
// name of the API resource
options.ApiName = "api1";
options.ApiSecret = "secret";
})
通常,您不希望為每個傳入請求執行到內省端點的往返。中間件有一個內置緩存,您可以像這樣啟用:
.AddIdentityServerAuthentication(options =>
{
// base-address of your identityserver
options.Authority = "https://demo.identityserver.io";
// name of the API resource
options.ApiName = "api1";
options.ApiSecret = "secret";
options.EnableCaching = true;
options.CacheDuration = TimeSpan.FromMinutes(10); // that's the default
})
處理程式將使用在DI容器中註冊的任何IDistributedCache實現(例如標準的MemoryDistributedCache)。
29.3 驗證範圍
所述ApiName屬性檢查該令牌具有匹配觀眾(或短aud
),如權利要求。
在IdentityServer中,您還可以將API細分為多個範圍。如果需要該粒度,可以使用ASP.NET Core授權策略系統來檢查範圍。
29.3.1 制定全球政策:
services
.AddMvcCore(options =>
{
// require scope1 or scope2
var policy = ScopePolicy.Create("scope1", "scope2");
options.Filters.Add(new AuthorizeFilter(policy));
})
.AddJsonFormatters()
.AddAuthorization();
29.3.2 制定範圍政策:
services.AddAuthorization(options =>
{
options.AddPolicy("myPolicy", builder =>
{
// require scope1
builder.RequireScope("scope1");
// and require scope2 or scope3
builder.RequireScope("scope2", "scope3");
});
});