asp.net-core - 在 Identity Server 4 中验证 JWT 不记名令牌
问题描述
我有一个基于 IdentityServer 4 运行的 Identity Server,并且我有一个内置于 ASP.Net Core Web API 的 ASP.NET WebAPI。我在身份服务器的 /connect/token 端点上成功登录。我想检查在我的 API 请求标头中发送的 JWT 不记名令牌的有效性。
这是我的启动 API 项目中的配置:
在配置服务中:
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
//base-address of my identityserver
options.Authority = "https://localhost:5000/";
//name of the API resource
options.ApiName = "API_Resource_Name";
});
在配置中:
app.UseAuthentication();
注意:我已经向我的控制器添加了授权注释
解决方案
将身份验证和授权添加到您的 API Startup.cs ConfigureServices:
services.AddAuthentication("bearer")
.AddJwtBearer("bearer", options =>
{
options.Authority = Configuration["Authority"];
options.Events = new Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/chathub")))
{
context.Token = accessToken;
}
return Task.CompletedTask;
},
OnTokenValidated = context =>
{
var token = context.SecurityToken as JwtSecurityToken;
if (token != null)
{
ClaimsIdentity identity = context.Principal.Identity as ClaimsIdentity;
if (identity != null)
{
identity.AddClaim(new Claim("access_token", token.RawData));
}
}
return Task.CompletedTask;
}
};
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false,
NameClaimType = "name",
RoleClaimType = "role"
};
});
接着...
services.AddAuthorization(options =>
{
options.AddPolicy("ApiScope", policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireClaim("scope", "SignalR.API");
});
});
内部配置...
app.UseAuthentication();
app.UseAuthorization();
推荐阅读
- sql-server - java.lang.NoSuchMethodError: com.microsoft.sqlserver.jdbc.SQLServerBulkCopyOptions.setAllowEncryptedValueModifications(Z)V
- javascript - javascript中的实例数组
- apache - 重写代码 htaccess 停止工作
- asp.net-mvc - ASP.NET MVC 在同一页面上显示输出
- wcf - 任何客户端都可以使用的具有复合类型的跨平台 WCF 服务
- spring-mvc - 使用 ContentCachingResponseWrapper 丢失标头
- c# - LINQ Conditional Where 子句包括多个条件
- python - Flask WTForms 用变量自动填充 StringField
- reactjs - 将 webpack-stream 与 gulp 一起使用时的奇怪行为
- powershell - 使用 powershell 获取对 Active Directory 分发列表的最新更改