1

I'm having trouble with 401 responses that cause a redirect (302) to the login page. My application uses both MVC and Web API. I'm using OpenID and Azure Active Directory to authenticate users, my auth setup is as follows:

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);

When a Web API call generates a 401, I want that status returned to the client. I've read lots of articles, like here, here and here, however I've been unable to get a working solution. I could return a 404, as suggested in a reply in the last link, however I would prefer not to do that. Can anyone suggest an approach?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
markpirvine
  • 1,485
  • 1
  • 23
  • 54

1 Answers1

2

Mixing authentication for MVC (as in web UX) and Web API requires special care. See here for an example of how you can combine the two. I know you already read a lot about the theory behind this, but you you want yet another (not required, the sample above alone should unblock you) backgrounder you can glance through this.

vibronet
  • 7,364
  • 2
  • 19
  • 21