我有一个基于 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();
注意:我已经向我的控制器添加了授权注释
答案 0 :(得分:0)
向您的 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();