如何在.NET Web应用中使用Azure App Service身份验证的用户角色?
问题描述
我在.NET Web应用中配置Azure App Service的Azure Active Directory(AAD)身份验证与授权,完成了以下操作:
- 将应用部署至App Service,启用Microsoft身份提供商,未认证请求自动重定向至登录页面,仅允许AAD目录内账户访问
- 在应用注册界面创建了
Admin和User两个应用角色,并为目录中的用户分别分配了对应角色
初始状态下,控制器中的HttpContext.User没有任何声明和标识。添加以下代码到Program.cs后,可正常获取到用户声明与标识:
builder.Services.AddMicrosoftIdentityWebAppAuthentication(builder.Configuration); builder.Services.AddAuthorization();
编写了如下控制器方法用于测试:
public IActionResult Index() { return Ok(new { Roles = HttpContext.User.Claims.FirstOrDefault(claim => claim.Type == "roles")?.Value, HasUserRole = HttpContext.User.IsInRole("User"), HasAdminRole = HttpContext.User.IsInRole("Admin"), UserIsAuthenticated = HttpContext.User.Identity?.IsAuthenticated, UserAuthType = HttpContext.User.Identity?.AuthenticationType, }); }
认证后的响应显示roles声明存在,但IsInRole始终返回false:
{ "roles": "User", "hasUserRole": false, "hasAdminRole": false, "userIsAuthenticated": true, "userAuthType": "aad" }
同时,标记了[Authorize(Roles = "User")]的端点会返回403错误,仅[Authorize]标记的端点可正常访问。尝试参考相关示例代码调整配置后,问题仍未解决。
解决方案
问题根源在于默认的身份验证配置未将AAD返回的roles声明映射到.NET身份系统的角色标识。需要显式指定角色声明的类型,让.NET正确识别AAD的角色信息。
修改Program.cs中的身份验证配置,添加角色声明映射:
builder.Services.AddMicrosoftIdentityWebAppAuthentication(builder.Configuration) .Configure(options => { // 指定AAD返回的roles字段作为.NET的角色声明类型 options.TokenValidationParameters.RoleClaimType = "roles"; }); builder.Services.AddAuthorization();
或者通过AddRoles方法配置:
builder.Services.AddMicrosoftIdentityWebAppAuthentication(builder.Configuration) .AddRoles(options => { options.RoleClaimType = "roles"; }); builder.Services.AddAuthorization();
配置完成后,HttpContext.User.IsInRole()方法将能正确识别用户的角色,[Authorize(Roles)]属性也会正常生效,带角色限制的端点不再返回403错误。
内容的提问来源于stack exchange,提问作者DrOverbuild
相关产品推荐
相关产品推荐

