我想通过userinfo端点获取自定义声明。这也有效,但所有自定义声明也都在访问令牌中。我以这种方式理解,有可能我可以在访问令牌中放置一个或两个声明(如电子邮件或名称),并通过userinfo端点访问所有其他声明(given_name,...)。 (并且它们不在访问令牌中)
我的ProfileService看起来像这样:
public class ProfileService : IProfileService
{
private readonly IUserClaimsPrincipalFactory<CustomUser> _claimsFactory;
private readonly UserManager<CustomUser> _userManager;
public ProfileService(UserManager<CustomUser> userManager, IUserClaimsPrincipalFactory<CustomUser> claimsFactory)
{
_claimsFactory = claimsFactory;
_userManager = userManager;
}
public async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
var sub = context.Subject.GetSubjectId();
var user = await _userManager.FindByIdAsync(sub);
var principal = await _claimsFactory.CreateAsync(user);
var claims = principal.Claims.ToList();
claims = claims.Where(claim => context.RequestedClaimTypes.Contains(claim.Type)).ToList();
claims.Add(new Claim(JwtClaimTypes.GivenName, user.FirstName));
context.IssuedClaims = claims;
}
public async Task IsActiveAsync(IsActiveContext context)
{
var sub = context.Subject.GetSubjectId();
var user = await _userManager.FindByIdAsync(sub);
context.IsActive = user != null;
}
}
这是我的config.cs文件:
return new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
new IdentityResources.Email(),
};
}
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource("api1", "My API", new [] {JwtClaimTypes.Name })
};
}
new Client
{
ClientId = "xxx",
ClientName = "xxx",
//AccessTokenType = AccessTokenType.Reference,
AccessTokenType = AccessTokenType.Jwt,
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,
RequireConsent = false,
RedirectUris = { "http://localhost:4200/home" },
PostLogoutRedirectUris = { "http://localhost:4200/unauthorized" },
AllowedCorsOrigins = { "http://localhost:4200" },
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.Email,
"api1"
}
}
};
我有没有理解它?
答案 0 :(得分:1)
GetProfileDataAsync
被调用两次,但具有不同的上下文。
Context.Caller
= ClaimsProviderAccessToken 。Context.Caller
= UserInfoEndpoint 。请注意,对于这两种情况,请求的声明都有所不同。
如果您只想为身份添加声明,您可以将身份服务器配置为通过将这些声明添加到过滤器(IdentityResource)来包含这些声明,在这种情况下,您不需要在{{{} {{ 1}}。或者,如果您要添加特定声明,请检查当前上下文。
所以在GetProfileDataAsync
中你可以得到以下内容:
GetProfileDataAsync
这应该仅将声明添加到userinfo。