title: Web API 401 Redirect Azure Active Directory OpenIdConnect
body: <p>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:</p>
  
  <pre><code>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) =&gt;
              {
                  string userId = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Name).Value;
  
                  IUserManager userManager = mvcApplication.CurrentContainer.Resolve&lt;IUserManager&gt;();
  
                  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 =&gt; c.Type == "groups" &amp;&amp; c.Value.Equals(AADClaimTypes.Super, StringComparison.CurrentCultureIgnoreCase));
  
                      if(groupSuper != null)
                      {
                          userManager.AddClaim(userId, CharitableClaimTypes.Super, userId);
                      }
                  }
  
                  List&lt;Claim&gt; claims = userManager.GetUserClaims(userId);
  
                  if(claims != null &amp;&amp; claims.Count() &gt; 0)
                  {
                      OpenIdClaimsAuthenticationManager openIdClaimsAuthenticationManager = new OpenIdClaimsAuthenticationManager();
  
                      openIdClaimsAuthenticationManager.Authenticate(context.AuthenticationTicket.Identity, claims);
                  }
  
                  return Task.FromResult(0);
              },
              RedirectToIdentityProvider = (context) =&gt;
              {
                  context.ProtocolMessage.RedirectUri = context.Request.Uri.ToString();
                  context.ProtocolMessage.PostLogoutRedirectUri = postLogoutRedirectUri;
  
                  return Task.FromResult(0);
              },
              AuthorizationCodeReceived = (context) =&gt;
              {
                  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);
  </code></pre>
  
  <p>When a Web API call generates a 401, I want that status returned to the client.  I've read lots of articles, like <a href="http://slynetblog.blogspot.co.uk/2014/03/preventing-302-redirect-for-aspnet.html" rel="nofollow noreferrer">here</a>, <a href="http://www.jayway.com/2014/09/25/securing-asp-net-web-api-endpoints-using-owin-oauth-2-0-and-claims/" rel="nofollow noreferrer">here</a> and <a href="https://stackoverflow.com/questions/20149750/unauthorised-webapi-call-returning-login-page-rather-than-401">here</a>, 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?</p>