我有一个基于IdentityServer 4的身份服务器,ASP.NET WebAPI是在ASP.Net Core中构建的。我在标识服务器的/connect/token端点上成功登录。我想检查在我的API请求的头中发送的JWT承载令牌的有效性。
这是我的启动API项目中的配置:
在ConfigureServices中:
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();注:我在控制器中添加了授权注释
发布于 2021-07-26 15:07:20
向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();https://stackoverflow.com/questions/68531577
复制相似问题