【发布时间】:2021-10-11 09:10:29
【问题描述】:
我正在将 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");
});
});
请指教我做错了什么?
【问题讨论】:
-
一切都错了。你只需要使用推荐的算法,而不是试图发明你自己的算法,如果不为你的算法创建一个新的网络框架就永远不会工作。
-
什么意思?我刚刚从 IdentityServer repo 复制了快速入门,并针对我的基础架构进行了调整。
标签: asp.net-core authentication identityserver4