emz*_*ero 5 c# asp.net claims-based-identity asp.net-identity-3 identityserver4
我有一个解决方案,包括:
oidc-client。当我创建新用户时,我设置了一些保存在AspNetUserClaims表中的自定义声明,如下所示:

然后,在我的 API 项目中,在控制器内我想要获取经过身份验证的用户的用户声明。
我本来希望this.User.Claims得到这些,但结果却返回了以下内容,这似乎是与客户端应用程序相关的声明,而不是与用户相关的声明。
如何address, location, tenant_role从 Web API 项目内的控制器访问这些自定义用户声明 ( )?
请记住,API 项目无权访问该类UserManager或任何ASP.NET Identity Core相关内容。
因此,我为了让我的自定义用户声明在每个 API 请求中可用,在ApiResourceIdentityServer 启动时设置时我必须执行以下操作。
//Config.cs
public static IEnumerable<ApiResource> GetApiResources()
{
ApiResource apiResource = new ApiResource("api1", "DG Analytics Portal API")
{
UserClaims =
{
JwtClaimTypes.Name,
JwtClaimTypes.Email,
AnalyticsConstants.TenantRoleClaim // my custom claim key/name
}
};
return new List<ApiResource>
{
apiResource
};
}
Run Code Online (Sandbox Code Playgroud)
此方法将传递给services.AddInMemoryApiResources(或您正在使用的任何存储方法)
IIdentityServerBuilder builder = services
.AddIdentityServer(options =>
{
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;
})
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApiResources()) // here
.AddInMemoryClients(Config.GetClients())
.AddAspNetIdentity<ApplicationUser>();
Run Code Online (Sandbox Code Playgroud)
通过这种设置,每当 API 端点被命中时,我的自定义TenantRole声明就会出现,因此我可以简单地User.FindFirst(AnalyticsConstants.TenantRoleClaim)获取它。
| 归档时间: |
|
| 查看次数: |
5493 次 |
| 最近记录: |