Azure Active Directory RBAC 未返回不记名 token 中的角色

标签 azure asp.net-core jwt azure-active-directory rbac

我正在将 Azure AD Basic 层与 ASP.NET Core API 结合使用,我已遵循 RBAC sample 。我已经在 list 中设置了一个具有角色的应用程序,如下所示:

appRoles": [
    {
      "allowedMemberTypes": [ "User" ],
      "displayName": "Read Device",
      "id": "b2e6f6c2-c3d5-4721-ad49-0eea255ccf45",
      "isEnabled": true,
      "description": "Can read a device.",
      "value": "read_device"
    },
    ...
]

我已将 API 设置为使用 UseJwtBearerAuthentication 中间件,如下所示:

application.UseJwtBearerAuthentication(
    new JwtBearerOptions()
    {
        AuthenticationScheme = "Azure Active Directory",
        Authority = options.Authority,
        Audience = options.ClientId,
        TokenValidationParameters = new TokenValidationParameters()
        {
            RoleClaimType = "roles",
            ValidateIssuer = false
        }
    })

我已向我的用户授予上述“读取设备”角色:

enter image description here

我正在使用 Swagger UI 进行调用以获取身份验证 token 。它调用以下 URL:

https://login.microsoftonline.com/[Tenant].onmicrosoft.com/oauth2/authorize?
    response_type=token
    &redirect_uri=http%3A%2F%2Flocalhost%3A5100%2Fswagger%2Fo2c.html
    &realm=-
    &client_id=[Client ID]
    &scope=http%3A%2F%2Fschemas.microsoft.com%2Fws%2F2008%2F06%2Fidentity%2Fclaims%2Frole
    &state=oauth2
    &resource=[Client ID]

我怀疑我没有将正确的值传递给 scope 参数,因此我尝试询问我能想到的每个 scope:

&scope=openid
    %20email
    %20profile
    %20offline_access
    %20user_impersonation
    %20roles
    %20http%3A%2F%2Fschemas.microsoft.com%2Fws%2F2008%2F06%2Fidentity%2Fclaims%2Frole
    %20read_device

如果我在 list 中设置"groupMembershipClaims": "All",我可以看到组声明,但我想要角色。我可以登录并调用我的 API,但是我从未在 JWT token 中取回任何角色,因此我无法检查用户角色。我做错了什么?

最佳答案

事实证明,我需要请求 id_token 而不是 tokenid_token 包含有关用户的额外声明/范围/资源。我还需要为每个请求提供一个包含新随机 GUID 的 nonce 参数。因此,我最终得到了以下 URL:

https://login.microsoftonline.com/[Tenant].onmicrosoft.com/oauth2/authorize?
    response_type=id_token
    &client_id=[Client ID]
    &redirect_uri=http%3A%2F%2Flocalhost%3A5000%2F
    &nonce=9ac5ad8d-df44-48e6-9bd6-e72743b3625c

关于Azure Active Directory RBAC 未返回不记名 token 中的角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42782631/

相关文章:

c# - ASP.NET Core IHostedService 手动启动/停止/暂停(?)

python - 如何使用 python falcon rest api 创建具有多个用户级别的 token 的用户身份验证

spring-boot - Spring Cloud Zuul 和 JWT 刷新 token

python - 如何在 azure 函数绑定(bind)中选择日期时间周数?

c# - 将 Azure AD 与 Microsoft.Owin.Security.OpenIdConnect 配合使用时抛出 "IDX10223: Lifetime validation failed. The token is expired."

Azure 应用程序设置不会覆盖我的 appsettings.json 文件值

asp.net-web-api - 请求完成后的处理

swift - 升级到 Swift 3.0 后未收到来自 Azure 的 APNS 消息

Azure:如何创建 WADLogsTable 来捕获诊断代码?

django - "This field is required."DRF