title: Configure Auth on Startup not working (OWIN) ASP.NET MVC
body: <p>I have a simple asp.net MVC application with an account controller with 2 action methods to sign in and sign out.</p>
  
  <p>My project has a custom _layout.cshtml from a theme we bought, but the server side logic was done based on this post:
  <a href="http://www.andrewconnell.com/azure-ad-asp-net-mvc-walk-through-implementing-adal-owin" rel="nofollow">http://www.andrewconnell.com/azure-ad-asp-net-mvc-walk-through-implementing-adal-owin</a></p>
  
  <p>If I put a breakoint on the AuthorizationCodeReceived in ConfigureAUth, this breakpoint is never hit.</p>
  
  <p>The azure SIGN IN Page is being shown when I click SIGN IN, but when it returns it doesnt show the Loginpartial view options where it says ITS AUTHENTICATED.</p>
  
  <p>So my conclussion it goes to azure aad, user enters email and password, its "authenticated", then it goes back to the app but it says its not authenticated.</p>
  
  <p>Very weird.</p>
  
  <p>SO I will paste the most important parts of the code.</p>
  
  <pre><code> public partial class Startup
      {
          // The Client ID is used by the application to uniquely identify itself to Azure AD.
          // The App Key is a credential used to authenticate the application to Azure AD.  Azure AD supports password and certificate credentials.
          // The Metadata Address is used by the application to retrieve the signing keys used by Azure AD.
          // The AAD Instance is the instance of Azure, for example public Azure or Azure China.
          // The Authority is the sign-in URL of the tenant.
          // The Post Logout Redirect Uri is the URL where the user will be redirected after they sign out.
          // This is the resource ID of the AAD Graph API.  We'll need this to request a token to call the Graph API.
          public static readonly string Authority = String.Format(CultureInfo.InvariantCulture, SettingsHelper.AADInstance, SettingsHelper.Tenant);
  
          public void ConfigureAuth(IAppBuilder app)
          {
              app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
              app.UseCookieAuthentication(new CookieAuthenticationOptions());
              app.UseOpenIdConnectAuthentication(
                  new OpenIdConnectAuthenticationOptions
                  {
                      ClientId = SettingsHelper.ClientId,
                      Authority = Authority,
                      PostLogoutRedirectUri = SettingsHelper.PostLogoutRedirectUri,
  
                      Notifications = new OpenIdConnectAuthenticationNotifications()
                      {
                          AuthorizationCodeReceived = (context) =&gt;
                          {
                              var code = context.Code;
                              ClientCredential credential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey);
                              string userObjectId = context.AuthenticationTicket.Identity.FindFirst(System.IdentityModel.Claims.ClaimTypes.NameIdentifier).Value;
                              EfAdalTokenCache sampleCache = new EfAdalTokenCache(userObjectId);
                              AuthenticationContext authContext = new AuthenticationContext(Authority, sampleCache);
                              AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, SettingsHelper.GraphResourceId);
                              return Task.FromResult(0);
                          },
                          AuthenticationFailed = context =&gt;
                          {
                              context.HandleResponse();
                              context.Response.Redirect("/Home/Error?message=" + context.Exception.Message);
                              return Task.FromResult(0);
                          }
                      }
                  });
          }
      }
  </code></pre>
  
  <p>The login partial, should show something like, Hello user! but it doesnt.</p>
  
  <pre><code>@using Microsoft.AspNet.Identity
  @if (Request.IsAuthenticated)
  {
      using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
      {
  
      &lt;ul class="nav navbar-top-links navbar-right"&gt;
          &lt;li class="dropdown"&gt;
              &lt;a class="dropdown-toggle count-info" data-toggle="dropdown" href="#"&gt;
                  @*@{ Html.RenderAction("GetModules", "Module"); }*@
              &lt;/a&gt;
          &lt;/li&gt;
          &lt;li&gt;
              @Session["DateAndTime"].ToString()
          &lt;/li&gt;
          &lt;li&gt;
              @Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage" })
          &lt;/li&gt;
          &lt;li&gt;@Html.ActionLink("Sign out", "SignOut", "Account")&lt;/li&gt;
      &lt;/ul&gt;
      }
  }
  else
  {
      &lt;ul class="nav navbar-top-links navbar-right"&gt;
          &lt;li&gt;@Html.ActionLink("Sign in", "SignIn", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })&lt;/li&gt;
      &lt;/ul&gt;
  }
  </code></pre>
  
  <p>The account controller</p>
  
  <pre><code> public class AccountController : Controller
      {
          public void SignIn()
          {
              // Send an OpenID Connect sign-in request.
              if (!Request.IsAuthenticated)
              {
                  HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectAuthenticationDefaults.AuthenticationType);
              }
          }
          public void SignOut()
          {
              // Remove all cache entries for this user and send an OpenID Connect sign-out request.
              //string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
              //AuthenticationContext authContext = new AuthenticationContext(Startup.Authority, new EfAdalTokenCache(userObjectID));
              //authContext.TokenCache.Clear();
  
              HttpContext.GetOwinContext().Authentication.SignOut(
                  OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);
          }
      }
  </code></pre>
  
  <p>and home controller</p>
  
  <pre><code>public class HomeController : Controller
      {
          public ActionResult Index()
          {
              //UserProfile up = Cache.GetUserProfile(ClaimsPrincipal.Current.Identities.First().Name);
              ViewData["SubTitle"] = "Welcome in ASP.NET MVC 5 INSPINIA SeedProject ";
              ViewData["Message"] = "It is an application skeleton for a typical MVC 5 project. You can use it to quickly bootstrap your webapp projects.";
              return View();
          }
  
          public ActionResult Minor()
          {
              ViewData["SubTitle"] = "Simple example of second view";
              ViewData["Message"] = "Data are passing to view by ViewData from controller";
              return View();
          }
      }
  </code></pre>
  
  <p>Update 1:
  When I go to:
  <a href="https://localhost:44300/" rel="nofollow">https://localhost:44300/</a></p>
  
  <p>And Click on the Sign In link</p>
  
  <p>It goes to: 
  <a href="https://localhost:44300/Account/SignIn" rel="nofollow">https://localhost:44300/Account/SignIn</a> sometimes, and some other times it goes to Azure, when it returns from Azure it returns to: <a href="https://localhost:44300/Account/SignIn" rel="nofollow">https://localhost:44300/Account/SignIn</a> instead of <a href="https://localhost:44300/" rel="nofollow">https://localhost:44300/</a></p>
  
  <p>but the SignIn breakpoint is never hit on the account controller!</p>