Azure AAD ClaimsPrincipal IsInRole始终返回false

时间:2017-07-13 14:34:13

标签: c# azure azure-active-directory claims-based-identity asp.net-mvc-5.2

我在使用Azure AAD appRoles和MVC时出现问题,我修改了清单,添加了一些角色并将其分配给了几个用户。

但是当我尝试使用User.IsInRole或ClaimsPrincipal.Current.IsInRole时,它总是返回false。

Click Here to see

在上面的屏幕截图{role:SuperAdmin}中,角色正在声明的json中返回。

我已经做了很多阅读,据我所知,我正在做正确的事但却找不到原因?

以下是我的Startup.Auth.cs

public partial class Startup
{
    private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
    private static string appKey = ConfigurationManager.AppSettings["ida:ClientSecret"];
    private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
    private static string tenantId = ConfigurationManager.AppSettings["ida:TenantId"];
    private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];

    public static readonly string Authority = aadInstance + tenantId;

    // This is the resource ID of the AAD Graph API.  We'll need this to request a token to call the Graph API.
    //string graphResourceId = "https://graph.windows.net";

    public void ConfigureAuth(IAppBuilder app)
    {
        ApplicationDbContext db = new ApplicationDbContext();

        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions());

        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = Authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,
                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                {
                    RoleClaimType= "roles"
                },
                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                    AuthorizationCodeReceived = (context) =>
                    {
                        var code = context.Code;
                        ClientCredential credential = new ClientCredential(clientId, appKey);
                        string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                        AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));

                        return Task.FromResult(0);
                    }
                }
            });
    }
}

1 个答案:

答案 0 :(得分:0)

由于您使用OpenID Connect Owin中间件从Azure AD登录用户,因此您无需启用App Service身份验证/授权功能,该功能为您的应用程序提供了一种登录用户的方式,以便您不必更改应用后端的代码。只需关闭App Service身份验证/授权功能。