Azure AD单租户Web API:授权策略返回403但角色声明存在
Azure AD角色授权403但声明存在的问题解决
问题根源
你犯了一个常见的配置错误:Web API使用的是JwtBearer认证方案,但你却去配置了OpenIdConnectOptions——这个配置是给MVC客户端用的,根本不会作用在Web API的令牌验证上。所以即使令牌里有roles声明,ASP.NET Core也没把它识别为角色,导致User.IsInRole()返回false,授权策略触发403。
修复方案
把RoleClaimType的配置放到JwtBearer的选项里,有两种实现方式:
方式一:在添加认证服务时直接配置
修改AddMicrosoftIdentityWebApiAuthentication的调用,直接传入配置委托:
services.AddMicrosoftIdentityWebApiAuthentication(Configuration, options => { options.TokenValidationParameters.RoleClaimType = "roles"; }) .EnableTokenAcquisitionToCallDownstreamApi() .AddMicrosoftGraph(Configuration.GetSection("DownstreamApi")) .AddInMemoryTokenCaches();
方式二:单独配置JwtBearerOptions
如果想保持原有代码结构,也可以单独配置JwtBearer的选项:
services.Configure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options => { options.TokenValidationParameters.RoleClaimType = "roles"; });
额外检查项
- 确保
JwtSecurityTokenHandler.DefaultMapInboundClaims = false;这行代码放在认证服务配置之前,防止默认的声明映射逻辑覆盖你的配置。 - 核对令牌中
roles声明的具体值,和你策略里的Constants.CAN_CREATE_ACCOUNT完全一致(大小写敏感,不能有拼写错误)。
内容的提问来源于stack exchange,提问作者Chukwuma Obi
相关产品推荐
相关产品推荐

