检查MVC应用程序中用户的角色以从Azure Active Directory授权

时间:2018-10-24 06:23:02

标签: azure asp.net-mvc-4 azure-active-directory azure-web-sites openid-connect

这是我在Startup.Auth.cs中的代码

 public void ConfigureAuth(IAppBuilder app)        {

       JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions());

        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer=false,
                    NameClaimType = "upn",
                   RoleClaimType ="roles"   
                }                   
            });
    }

在我的MVC视图中,我正在检查@ User.IsInRole(“ CBUser”),由于用户具有CBUSer角色,因此返回True。所有这些代码在带有Azure AD身份验证和授权的Visual Studio中都可以正常工作。但是,当我将应用程序移动到Azure时,@ User.IsInRole(“ CBUser”)始终返回false。如何在MVC View或Controller中读取用户角色。我尝试下面的代码读取在VS2015中调试时可以正常工作的用户角色。但是一旦应用程序移至Azure环境后将无法正常工作

            var appRoles = new List<string>();
        foreach (Claim claim in ClaimsPrincipal.Current.FindAll("roles"))
                appRoles.Add(claim.Value);

1 个答案:

答案 0 :(得分:0)

您发布的代码似乎很好。也许您可以看一下官方示例:Authorization in a web app using Azure AD application roles & role claims

此外,您可以远程调试Web应用程序:Troubleshoot a web app in Azure App Service using Visual Studio