Search code examples
c#asp.net-coreasp.net-core-identity

Logging out from Identity after cookie has expired causes http error 400


In my _LoginPartial.cshtml I have this logout-button:

<form id="logoutForm" class="form-inline" asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="@Url.Action("Index", "", new { area = "" })">
    <button id="logout" type="submit">
        Log out
    </button>
</form>

Then, from what I can gather, Logout.cshtml.cs is called:

public class LogoutModel : PageModel
{
    private readonly SignInManager<ApplicationUser> _signInManager;
    private readonly ILogger<LogoutModel> _logger;

    public LogoutModel(SignInManager<ApplicationUser> signInManager, ILogger<LogoutModel> logger)
    {
        _signInManager = signInManager;
        _logger = logger;
    }

    public void OnGet()
    {
    }

    public async Task<IActionResult> OnPost(string returnUrl = null)
    {
        await _signInManager.SignOutAsync();
        _logger.LogInformation("User logged out.");
        if (returnUrl != null)
        {
            return LocalRedirect(returnUrl);
        }
        else
        {
            return RedirectToPage();
        }
    }
}

But if the user session cookie has expired when the user presses "Log out", I get this descriptive error message:

HTTP ERROR 400

Any breakpoints set anywhere in Logout.cshtml.cs is never hit.

What is happening?


Solution

  • if the user session cookie has expired when the user presses "Log out", I get this descriptive error message:

    HTTP ERROR 400

    Any breakpoints set anywhere in Logout.cshtml.cs is never hit.

    As we know, Razor Pages are protected from XSRF/CSRF automatically. And the antiforgery token (associated with the current user's identity) that client user sent to server would cause verification fail if current user's authentication expired, which cause above error.

    To fix above error, you can apply IgnoreAntiforgeryToken Attribute to LogoutModel class, like below.

    [AllowAnonymous]
    [IgnoreAntiforgeryToken]
    public class LogoutModel : PageModel
    { 
    

    You can get detailed information about "Prevent Cross-Site Request Forgery (XSRF/CSRF) attacks" from following doc:

    https://learn.microsoft.com/en-us/aspnet/core/security/anti-request-forgery?view=aspnetcore-3.1