ASP.NET MVC logout and re-login

Hello,

I have a simple Asp.Net MVC application that is using Okta.Aspnet middleware.
If I am using Session (see Claims action), I can login and logout, but the 2nd login will not authenticate the user. If I comment the line with the Session, I can login/logout and then re-login successfully.
Any idea how I can re-login multiple times, even if I use Session?

Here is the code for the Account controller:

public class AccountController : Controller
{
public ActionResult Login()
{
if (!HttpContext.User.Identity.IsAuthenticated)
{
var props = new AuthenticationProperties
{
RedirectUri = Url.Action(“ExternalLoginCallback”, “Account”),
};

         HttpContext.GetOwinContext().Authentication.Challenge(props, OpenIdConnectAuthenticationDefaults.AuthenticationType);
         
         return new HttpUnauthorizedResult();
     }

     return RedirectToAction("claims", "account");
 }

 [AllowAnonymous]
 [HttpGet]
 public async Task<ActionResult> ExternalLoginCallback()
 {
     //ExternalLoginInfo loginInfo = await HttpContext.GetOwinContext().Authentication.GetExternalLoginInfoAsync();

     //if (loginInfo == null)
     //{
     //    return RedirectToAction("Login");
     //}

     return RedirectToAction("claims", "account");
 }

 [HttpPost]
 public ActionResult Logout()
 {
     if (HttpContext.User.Identity.IsAuthenticated)
     {
         HttpContext.GetOwinContext().Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType, 
             OktaDefaults.MvcAuthenticationType);
     }

     return RedirectToAction("Index", "Home");
 }

 public ActionResult PostLogout()
 {
     return RedirectToAction("Index", "Home");
 }

 public async Task<ActionResult> Claims()
 {
     Session["Test"] = "Test";

     var isAuthenticated = HttpContext.User.Identity.IsAuthenticated;

     return View(HttpContext.GetOwinContext().Authentication.User.Claims);
 }

}

If you are using .NET framework, this might be due to how cookies are handled when using OWIN and system.web Session object at the same time. To overcome this, you can try updating your startup.cs CookieAuthentication configuration like below

app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                // ...
                CookieManager = new SystemWebCookieManager()
            });

This is documented in Katana wiki here.

If you upgrade to dotnet core, this will be handled out of the box.

2 Likes

That fixed my issue. Thank you so much for your quick reply.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.