简体   繁体   中英

Razor Pages - HTTP Error 400 (Invalid Anti Forgery Token) when idle the web site

I'm developing a web site in Blazor Server Side. My Login page is a Razor Page and everything works as expected, but if a user leaves their browser open for a period of time around 20 minutes and then performs the login they get an Http Error 400. I think it is for the Anti Forgery Token, because if you delete the cookie ".AspNetCore.Antiforgery" you got the same error. What should I do to solve this issue? What do you recommend?

If the application is being hosted in IIS I recommend setting Load User Profile = True in the application's app pool > Advanced settings menu. I had a similar issue in the past and I noticed every time the application restarted in IIS the keys were not persisted and any form opened before the restart is useless. However as soon as I changed the setting the key persisted. https://codeshorts.com/ASP-NET-Core-IIS-Invalid-Anti-Forgery-Token-Error-400

This also seems to have been an issue with Azure hosted apps https://stackoverflow.com/a/52302702/1843966

You can try to apply IgnoreAntiforgeryToken Attribute to LoginModel class to skip antiforgery token validation, like below.

[AllowAnonymous]
[IgnoreAntiforgeryToken]
public class LoginModel : PageModel
{
    //...

Note: normally, disabling antiforgery token validation is not recommended. But in this thread, applying it to LoginModel (user login functionality) should be fine.

I found this approach using code so you can catch the exception if it does fail

在此处输入图像描述

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