0

我正在尝试使用以下内容来确定 Azure AD B2C 登录用户是否是管理员:

if (User.IsInRole("Administrator")) 
{
    .... Display special info for Admins ....
}

但是,当我查看该System.Security.Principal.IPrincipal.User对象时,我会看到null该用户拥有的角色列表:

在此处输入图像描述

以下是配置身份验证和请求的相关代码TokenValidationParameters,包括要验证的角色。我尝试了以下方法:RoleClaimType = "role"RoleClaimType = "roles",这两种方法都不适合我。

    public void ConfigureAuth(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseKentorOwinCookieSaver();

        app.UseCookieAuthentication(new CookieAuthenticationOptions()
        {
            CookieSecure = CookieSecureOption.Always
        });

        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                // Generate the metadata address using the tenant and policy information
                MetadataAddress = String.Format(AadInstance, Tenant, DefaultPolicy),

                // These are standard OpenID Connect parameters, with values pulled from web.config
                ClientId = ClientId,
                Authority = Authority,
                PostLogoutRedirectUri = RedirectUri,
                RedirectUri = RedirectUri,

                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    RedirectToIdentityProvider = OnRedirectToIdentityProvider,
                    AuthenticationFailed = OnAuthenticationFailed,
                    AuthorizationCodeReceived = OnAuthorizationCodeReceived
                },

                /////////// HERE //////////
                // Specify the claims to validate
                TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = "name",
                    RoleClaimType = "role",
                },

                // Specify the scope by appending all of the scopes requested into one string (seperated by a blank space)
                Scope = $"{OpenIdConnectScopes.OpenId} {ReadTasksScope} {WriteTasksScope}"
            }
        );
    }

但是,当我对id_token从身份验证过程中检索到的内容进行解码并使用工具https://jwt.ms/对其进行解码时,我没有看到“角色”声明,如屏幕截图所示。

在此处输入图像描述

此外,在 SignIn Azure AD B2C 策略中,也许我需要添加一个“角色”ClaimType?

在此处输入图像描述

请帮忙!User.IsInRole("Administrator")为了上班,我还需要做什么?谢谢!

4

1 回答 1

0

为了解决这个问题,我最终使用 Azure AD Graph Client 来查询属于具有指定objectId. 这是我添加的方法:

    public async Task<string> GetUserRoleByObjectId(string objectId)
    {
        return await SendGraphGetRequest("/users/" + objectId + "/$links/memberOf", null);
    }

我在以下示例代码中将此方法添加到B2CGraphClient.cs文件中,并将其集成到我的 Web 应用程序中:https ://github.com/AzureADQuickStarts/B2C-GraphAPI-DotNet

于 2018-03-26T20:43:59.060 回答