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核心应用程序中的自定义声明
- 输入按键事件处理程序 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
