添加Authorize(Roles =“ foo”)会导致Azure身份验证后的无限重定向

时间:2018-08-28 17:38:19

标签: c# asp.net asp.net-mvc azure-active-directory openid-connect

我有一个MVC项目,该项目使用Azure AD作为用于用户的单点登录身份验证的连接服务。一切正常,任何具有[Authorize]属性的控制器都可以正常工作。

我在Azure中为此应用程序定义了两个应用程序角色,并且已将我自己分配给这两个应用程序角色。但是,当我将[Authorize(Roles="foo")]添加到控制器时,应用程序将重定向到Microsoft,以请求另一个登录,然后永远继续执行此操作。我无法确定这些角色是否没有通过令牌传递回去,或者MVC是否无法拾取要传递回的角色。

我已经尝试过使用 KentorOwinCookieSaver ,但这似乎并不能解决问题。

我还需要采取其他步骤来使MVC识别Azure appRoles吗?我没有使用Identity Manager或在数据库中存储任何用户信息。

这是我的Startup.Auth

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

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        { CookieSecure = CookieSecureOption.Always,
        CookieManager = new Microsoft.Owin.Host.SystemWeb.SystemWebChunkingCookieManager()});

        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = Authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,

                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 NaiveSessionCache(signedInUserID));
                        return authContext.AcquireTokenByAuthorizationCodeAsync(
                           code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);
                    },
                    AuthenticationFailed = (context) =>
                    {
                        context.HandleResponse();
                        context.Response.Redirect("/Home/Error?message=" + context.Exception.Message);
                        return Task.FromResult(0);
                    }
                }
            });
    }

1 个答案:

答案 0 :(得分:0)

事实证明,这是我可笑的错误。在再次查看令牌后,在Win的提示下,并将其与Azure门户中的应用程序注册清单进行比较,我看到了问题。我试图使用角色的“ displayName”(即管理屏幕上显示的),而不是“值”(可以预见的是随令牌返回的值)。

糟糕。