简体   繁体   中英

How do I invalidate an authentication cookie in ASP.NET Core?

I am having trouble invalidating an authentication cookie in ASP.NET Core 3.0.

Scenario

I have a user who is logged into the website. When they click the logout button it calls the following code:

[HttpGet]
public async Task<IActionResult> Logout()
{
    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
    HttpContext.Session.Clear();

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

This successfully clears all the cookies in the browser, however, if I grab the value of the session cookie .AspNetCore.Cookies prior to signing out, then add it back in on a future request, I am able to navigate to the pages which require user authentication.

Anyone able to help with this?

Note: The original question was regarding how to clear user session but I have since realised that this is actually an issue regarding the cookie itself and not server-side session.

This is how I do my logout method:

/// <summary>
/// Do the logout
/// </summary>
/// <returns></returns>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task Logout()
{
    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
    await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);

    //Important, this method should never return anything.
}

The trick here is to have the method not returning anything, as the SignOut method will generate its own response internally to the browser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM