How to access custom claim in aspnet core application authorized using Identity Server(如何访问使用Identity Server授权的ASPnet核心应用程序中的自定义声明)
问题描述
我正在遵循Identity Server快速入门模板,并尝试设置以下内容
- 身份服务器ASPnet核心应用
- MVC客户端,它向IS4进行身份验证,并调用受保护的API资源WebAPI客户端。
ApplicationUser有一个额外的列,我将其添加到来自ProfileService的索赔中,如下所示:
public async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
var sub = context.Subject.GetSubjectId();
var user = await _userManager.FindByIdAsync(sub);
if (user == null)
return;
var principal = await _claimsFactory.CreateAsync(user);
if (principal == null)
return;
var claims = principal.Claims.ToList();
claims.Add(new Claim(type: "clientidentifier", user.ClientId ?? string.Empty));
// ... add roles and so on
context.IssuedClaims = claims;
}
最后是MVC客户端APP中的配置ConfigureServices方法:
JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
}).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
.AddOpenIdConnect("oidc", options =>
{
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.ClientId = "mvc";
options.ClientSecret = "mvc-secret";
options.ResponseType = "code";
options.SaveTokens = true;
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("offline_access");
options.Scope.Add("api1");
options.GetClaimsFromUserInfoEndpoint = true;
options.ClaimActions.MapUniqueJsonKey("clientidentifier", "clientidentifier");
});
将GetClaimsFromUserInfoEndpoint设置为true时,我可以访问User.Identity中的自定义声明,但这会导致对ProfileService进行2次调用。
如果我删除或设置为False,则此声明仍然是Access_Token的一部分,但不是id_Token的一部分,然后我无法从上下文用户访问此特定声明。
有没有更好的方法可以从用户主体访问此声明,而不会导致2次调用(就像现在一样)?或者从上下文中读取Access_Token,并在检索到令牌后更新用户声明?谢谢:)
推荐答案
发现标识服务器中的Client对象具有执行该工作的属性:
//
// Summary:
// When requesting both an id token and access token, should the user claims always
// be added to the id token instead of requring the client to use the userinfo endpoint.
// Defaults to false.
public bool AlwaysIncludeUserClaimsInIdToken { get; set; }
如将客户端的lib元数据设置为True中所述,客户端不必从端点重新获取声明
谢谢大家:)
这篇关于如何访问使用Identity Server授权的ASPnet核心应用程序中的自定义声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何访问使用Identity Server授权的ASPnet核心应用程序中的自定义声明
基础教程推荐
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
