无法将Role添加至OpenIddict生成的JWT Token中
问题描述
我希望使用OpenIddict生成包含role=root的JWT Token,提交的请求参数如下:
{ "aud": "audience_01", "client_id": "client_01", "role": "root", "scope": "scope_01" }
但当前返回的JWT Token Payload中并未包含预期的role=root,Payload内容如下:
{ "sub": "client_01", "oi_prst": "client_01", "client_id": "client_01", "oi_tkn_id": "2179f976-89f3-49ba-bb86-cefa0523a627", "aud": "audience_01", "scope": "scope_01", "jti": "fa97eaf2-4716-45fa-9f03-aab977873386", "exp": 1701893995, "iss": "https://localhost:22401/", "iat": 1701807595 }
使用的代码如下:
[HttpPost("~/connect/token")] public async ValueTask<IActionResult> Exchange() { //retrieve OIDC request from original request var request = HttpContext.GetOpenIddictServerRequest() ?? throw new InvalidOperationException("The OpenID Connect request cannot be retrieved."); if (request.IsClientCredentialsGrantType()) { var clientId = request.ClientId; var identity = new ClaimsIdentity(authenticationType: TokenValidationParameters.DefaultAuthenticationType, nameType: Claims.Name, roleType: Claims.Role ); identity.AddClaim(Claims.Subject, clientId); identity.AddClaim(Claims.Name, "claims_name"); identity.AddClaim(Claims.Role, "root"); identity.SetScopes(request.GetScopes()); identity.SetResources(await _scopeManager.ListResourcesAsync(identity.GetScopes()).ToListAsync()); var principal = new ClaimsPrincipal(identity); // Returning a SignInResult will ask OpenIddict to issue the appropriate access/identity tokens. return SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); } throw new NotImplementedException("The specified grant type is not implemented."); }
解决方案
OpenIddict默认不会自动将role声明包含到JWT Token中,可通过以下两种方式解决:
方式一:通过作用域和声明映射配置
添加
roles作用域
修改请求参数的scope字段,加入roles:{ "aud": "audience_01", "client_id": "client_01", "role": "root", "scope": "scope_01 roles" }也可以在代码中强制追加该作用域,避免依赖请求参数:
var scopes = request.GetScopes().Union(new[] { "roles" }); identity.SetScopes(scopes);配置OpenIddict注册
role声明
在OpenIddict服务配置中,明确注册role声明,确保其被包含到令牌中:services.AddOpenIddict() .AddServer(options => { options.SetTokenEndpointUris("/connect/token"); // 其他已有配置... // 注册role声明,允许其出现在令牌中 options.RegisterClaims(Claims.Role); });
方式二:手动指定声明的令牌目标
添加role声明时,直接指定该声明要写入访问令牌,无需依赖roles作用域:
identity.AddClaim(Claims.Role, "root", OpenIddictConstants.Destinations.AccessToken);
原因说明
OpenIddict遵循OpenID Connect规范,仅当声明对应的作用域被请求,或者声明明确指定了目标令牌时,才会将声明包含到生成的Token中,默认不会自动包含自定义声明。
内容的提问来源于stack exchange,提问作者sc-info
相关产品推荐
相关产品推荐

