OpenIddict Claim destinations
时间:2022-09-23
ClaimsPrincipal
在登录操作期间
生成授权代码、刷新令牌和设备/用户代码时,OpenIddict 会自动将所有声明复制到生成的代码/令牌中。这是一个安全的操作,因为这些令牌始终是加密的,除了 OpenIddict 本身之外,任何人都无法读取(请求它们的用户或客户端应用程序无法读取它们的内容)。
对于访问令牌和身份令牌,情况有所不同,因为这些令牌旨在由不同的各方读取:
- 客户端应用程序可以完全访问它们收到的身份令牌中包含的声明。
- 资源服务器应该能够读取 API 调用中使用的访问令牌中包含的声明。
- 对于桌面、移动或基于浏览器的应用程序,用户通常不难访问身份令牌(例如,通过使用 Fiddler 拦截 HTTP 响应、使用开发人员工具或转储客户端进程的内存)。
- 如果明确禁用访问令牌加密,则客户端应用程序或用户自己可以访问访问令牌的内容(例如,通过复制令牌有效负载并使用https://jwt.io/等工具)。
由于这些原因, OpenIddict 不会自动复制附加到访问或身份令牌的声明ClaimsPrincipal
(sub
声明除外,它是 OpenIddict 中唯一的强制声明)。要允许 OpenIddict 将特定声明保留到访问或身份令牌,必须将称为“声明目标”的标志添加到Claim
您要公开的每个实例。
笔记
要将一个或多个目的地附加到声明,请使用claim.SetDestinations()
中定义的扩展名OpenIddict.Abstractions
。在典型情况下,授予的范围可用于确定允许将哪些声明复制到访问和身份令牌,如本例所示:
var principal = await _signInManager.CreateUserPrincipalAsync(user);
// Note: in this sample, the granted scopes match the requested scope
// but you may want to allow the user to uncheck specific scopes.
// For that, simply restrict the list of scopes before calling SetScopes().
principal.SetScopes(request.GetScopes());
principal.SetResources(await _scopeManager.ListResourcesAsync(principal.GetScopes()).ToListAsync());
foreach (var claim in principal.Claims)
{
claim.SetDestinations(claim.Type switch
{
// If the "profile" scope was granted, allow the "name" claim to be
// added to the access and identity tokens derived from the principal.
Claims.Name when principal.HasScope(Scopes.Profile) => new[]
{
OpenIddictConstants.Destinations.AccessToken,
OpenIddictConstants.Destinations.IdentityToken
},
// Never add the "secret_value" claim to access or identity tokens.
// In this case, it will only be added to authorization codes,
// refresh tokens and user/device codes, that are always encrypted.
"secret_value" => Array.Empty<string>(),
// Otherwise, add the claim to the access tokens only.
_ => new[]
{
OpenIddictConstants.Destinations.AccessToken
}
});
}
return SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
特别声明:本站部分内容收集于互联网是出于更直观传递信息的目的。该内容版权归原作者所有,并不代表本站赞同其观点和对其真实性负责。如该内容涉及任何第三方合法权利,请及时与824310991@qq.com联系,我们会及时反馈并处理完毕。