1

我在处理导致重定向 (302) 到登录页面的 401 响应时遇到问题。我的应用程序同时使用 MVC 和 Web API。我使用 OpenID 和 Azure Active Directory 对用户进行身份验证,我的身份验证设置如下:

private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
private static string appKey = ConfigurationManager.AppSettings["ida:AppKey"];
private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
private static string graphResourceId = ConfigurationManager.AppSettings["ida:GraphResourceId"];
public static readonly string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);

MvcApplication mvcApplication = HttpContext.Current.ApplicationInstance as MvcApplication;

public void ConfigureAuth(IAppBuilder app)
{
    OpenIdConnectAuthenticationOptions openIdConnectAuthenticationOptions = new OpenIdConnectAuthenticationOptions
    {
        ClientId = clientId,
        Authority = authority,
        PostLogoutRedirectUri = postLogoutRedirectUri,
        AuthenticationMode = AuthenticationMode.Active,
        Notifications = new OpenIdConnectAuthenticationNotifications()
        {
            SecurityTokenValidated = (context) =>
            {
                string userId = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Name).Value;

                IUserManager userManager = mvcApplication.CurrentContainer.Resolve<IUserManager>();

                if(!userManager.IsUserEnrolled(userId))
                {
                    string givenName = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.GivenName).Value;
                    string surname = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Surname).Value;

                    userManager.EnrolUser(userId, givenName, surname);

                    Claim groupSuper = context.AuthenticationTicket.Identity.Claims.FirstOrDefault(c => c.Type == "groups" && c.Value.Equals(AADClaimTypes.Super, StringComparison.CurrentCultureIgnoreCase));

                    if(groupSuper != null)
                    {
                        userManager.AddClaim(userId, CharitableClaimTypes.Super, userId);
                    }
                }

                List<Claim> claims = userManager.GetUserClaims(userId);

                if(claims != null && claims.Count() > 0)
                {
                    OpenIdClaimsAuthenticationManager openIdClaimsAuthenticationManager = new OpenIdClaimsAuthenticationManager();

                    openIdClaimsAuthenticationManager.Authenticate(context.AuthenticationTicket.Identity, claims);
                }

                return Task.FromResult(0);
            },
            RedirectToIdentityProvider = (context) =>
            {
                context.ProtocolMessage.RedirectUri = context.Request.Uri.ToString();
                context.ProtocolMessage.PostLogoutRedirectUri = postLogoutRedirectUri;

                return Task.FromResult(0);
            },
            AuthorizationCodeReceived = (context) =>
            {
                Claim objectIdentifierClaim = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier");

                if(objectIdentifierClaim != null)
                {
                    ClientCredential credential = new ClientCredential(clientId, appKey);
                    string objectIdentifier = objectIdentifierClaim.Value;
                    string code = context.Code;
                    Uri redirectUri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));

                    AuthenticationContext authContext = new AuthenticationContext(authority);//, new NaiveSessionCache(objectIdentifier));
                    AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(code, redirectUri, credential, graphResourceId);
                }

                return Task.FromResult(0);
            }

        }
    };

    CookieAuthenticationOptions cookieAuthenticationOptions = new CookieAuthenticationOptions()
    {
        AuthenticationType = OpenIdConnectAuthenticationDefaults.AuthenticationType
    };

    app.SetDefaultSignInAsAuthenticationType(OpenIdConnectAuthenticationDefaults.AuthenticationType);// CookieAuthenticationDefaults.AuthenticationType);
    app.UseCookieAuthentication(cookieAuthenticationOptions);
    app.UseOpenIdConnectAuthentication(openIdConnectAuthenticationOptions);

当 Web API 调用生成 401 时,我希望将该状态返回给客户端。我已经阅读了很多文章,例如这里这里这里,但是我一直无法获得有效的解决方案。正如最后一个链接中的回复所建议的那样,我可以返回 404,但我不希望这样做。任何人都可以提出一种方法吗?

4

1 回答 1

2

MVC(如在 Web UX 中)和 Web API 的混合身份验证需要特别小心。有关如何将两者结合起来的示例,请参见此处。我知道您已经阅读了很多关于这背后的理论,但是您还想要另一个(不是必需的,仅上面的示例就可以解除您的障碍)背景资料,您可以浏览一下

于 2015-03-04T22:34:38.967 回答