我正在将 Identity Server 添加到我现有的项目中。基本上我已经准备好了一切,但是当我向 API 发出请求时,User.Identity.Name
一片空白。但是,那User.Identity.Claims
包含名称声明:
我知道通过以下方式获取用户名的方法HttpContext.User.FindFirstValue(ClaimTypes.Name)
,但是这需要大量的代码重构,所以我宁愿避免这种方式。
我按照以下方式在身份服务器中配置了 ApiResources:
public static IEnumerable<ApiResource> ApiResources => new[]
{
new ApiResource
{
Name = "my-api",
DisplayName = "My API",
Description = "My API",
Scopes = new List<string> { "my-api"},
UserClaims = new List<string> {
JwtClaimTypes.Email,
JwtClaimTypes.Name,
JwtClaimTypes.Subject,
JwtClaimTypes.Role,
}
}
};
和客户:
public static IEnumerable<Client> Clients =>
new List<Client>
{
new Client
{
// ...
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.Email,
"name",
"roles",
"my-api",
}
}
};
API项目中的身份验证设置:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
options.Authority = config["IdentityServer:Domain"];
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = config["IdentityServer:Domain"],
ValidateAudience = false
};
});
services.AddAuthorization(options =>
{
options.AddPolicy("ApiScope", policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireClaim("scope", "my-api");
});
});
请建议我做错了什么?