我在 .NET Core 3.1 上,我正在尝试向 JWT 令牌添加自定义声明,但我无法这样做。如果您查看下面的代码,我可以使用这行代码读取自定义令牌
User.Claims.Where(x => x.Type == "role")
但是当我获取 JWT 令牌并将其放入 JWT.ms 时,令牌中不存在新的自定义声明。
.OnTokenValidated
是我在 idp 返回令牌之前尝试将自定义声明添加到令牌的事件。
AddOpenIdConnect("test",o => {
o.SignInScheme = "Cookies";
o.SignOutScheme = "Cookies";
o.ClientId = "f";
o.ClientSecret = "0e";
o.Authority = "https://test.com";
o.ResponseType = OpenIdConnectResponseType.Code;
o.MetadataAddress = "https://test.com/.well-known/openid-configuration";
**o.Events.OnTokenValidated = async (ctx) =>
{
var claimsIdentity = ctx.Principal.Identity as ClaimsIdentity;
claimsIdentity.AddClaim(new Claim("role", "Admin"));
};**
o.SaveTokens = true;
o.GetClaimsFromUserInfoEndpoint = true;
首先,一些基础知识:
当您使用此代码时:
claimsIdentity.AddClaim(new Claim("role", "Admin"));
您正在将其添加到从 ID-Token 创建的用户 (ClaimsPrincipal)。然后,此声明通常保存在本地会话 cookie 中。所以这一行从不修改任何标记。
也许您可以尝试在授权服务中添加该声明?
为了补充这个答案,我写了一篇更详细的博客文章 关于这个主题:在 ASP.NET Core 中调试 OpenID Connect 声明问题