【发布时间】:2020-07-24 10:43:10
【问题描述】:
我正在关注 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 Client 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 的两次调用。
如果我删除或设置为 false,则此声明仍然是 access_token 的一部分,但不是 id_token 的一部分,然后我无法从上下文用户访问此特定声明。
有没有更好的方法可以从用户主体访问此声明而不会导致 2 次调用(就像现在一样)?或者也许从上下文中读取 access_token 并在检索到令牌后更新用户声明?
谢谢:)
【问题讨论】:
-
@RuardvanElburg 不是真的。在问这个问题之前我看到了那个线程。一个理想的解决方案是只调用一次端点,而不是根据调用者修改响应。我期待某种中间件或事件,这些声明将从 access_token 中获取并放入 id 令牌,或任何其他线索,了解其他人如何做到这一点
-
这不是它的工作原理。 IdentityServer 发出令牌,并且对于每个令牌,使用不同的上下文调用该方法。您可以将客户端配置为仅请求访问令牌,但不能将此令牌更改为身份令牌。如果两者都需要,则需要两次调用。
-
如果是这样的话,我会保持这样,因为我需要它们。
标签: c# asp.net-core identityserver4