如何在 ASP.NET Core MVC 中获取 Azure Active Directory 的应用程序角色?

问题描述 投票:0回答:2

我创建了一个新的 ASP.NET Core MVC 6.0 Web 应用程序,并将其定义为使用 Microsoft Identity Platform 进行身份验证,如下所示:

现在我读了这篇文章,它展示了我们如何在 AD 应用程序中定义不同的角色并为他们分配用户@

https://learn.microsoft.com/en-us/azure/active-directory/develop/howto-add-app-roles-in-azure-ad-apps

所以我访问了Azure中的“ad”应用程序>>我添加了一个名为“admins”的角色,如下所示:-

但我不确定如何根据 ASP.NET Core MVC Web 应用程序中的登录用户检查此角色(“管理员”)?我可以使用

[Authorized]
属性来检查这些角色吗?有人可以帮忙吗?

谢谢

asp.net-core azure-active-directory asp.net-core-mvc asp.net-core-identity
2个回答
1
投票

我同意@Mohammad Hannan,您将获得的代币将具有这些角色。

我尝试在我的环境中重现相同的结果并得到以下结果:

我创建了与您相同的应用程序,并添加了应用程序角色,如下所示:

enter image description here

您可以将此应用程序角色分配给用户或组,如下所示:

转到 Azure 门户 -> Azure AD -> 企业应用程序 -> 您的应用程序 -> 用户和组 -> 添加用户/组

enter image description here

现在,在应用程序中添加此API权限,并确保授予管理员同意,如下所示:

enter image description here

我通过 Postman 使用客户端凭据流生成了访问令牌,如下所示:

POST https://login.microsoftonline.com/<tenantID>/oauth2/v2.0/token
client_id:<appID>
grant_type:client_credentials
scope: api://<appID/.default
client_secret: <secret>

回复:

enter image description here

当我在 jwt.ms 中解码上述令牌时,我得到

roles
成功声明,如下所示:

enter image description here


0
投票

在 ASP.NET Core Web 应用程序的上下文中,您可以拦截经过验证的传入 JWT 令牌并将角色声明提取到当前主体的身份中。请查看以下代码以供参考。

之后您可以轻松使用 ASP.NET 中现有的角色支持:

    控制器或操作上的
  • Authorize
    属性:
[Authorize(Roles = "admin.all")]
public class MyController: ControllerBase
{
 ...
}
  • HttpContext
  • 检查当前用户分配的角色
HttpContext.User.IsInRole("admin.all")

角色声明提取代码

   services
     .AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
     .AddMicrosoftIdentityWebApp(options =>
     {
       options.Events = new OpenIdConnectEvents()
       {
         OnTokenValidated = context =>
         {
           if (context.Principal.Identity is ClaimsIdentity identity)
           {
             var tokenRoleClaims = context.SecurityToken?.Claims.Where(c => c.Type == "roles") ?? Array.Empty<Claim>();
             var identityRoleClaims = tokenRoleClaims.Select(c => new Claim(identity.RoleClaimType, c.Value));
             identity.AddClaims(identityRoleClaims);
           }

           return Task.CompletedTask;
         }
       };
     });

© www.soinside.com 2019 - 2024. All rights reserved.