AntiForgeryToken Expiration Blank Page

postman antiforgerytoken
antiforgerytoken net core
generate antiforgerytoken in controller
anti forgery token for get request
asp net core antiforgerytoken ajax
catch anti-forgery exception
antiforgeryconfig suppressidentityheuristicchecks
system web mvc httpantiforgeryexception

I'm using IdentityServer4 with ASP.NET Core 2.2. On the Post Login method I have applied the ValidateAntiForgeryToken. Generally after 20 minutes to 2 hours of sitting on the login page and then attempting to login it produces a blank page.

If you look at Postman Console you get a 400 Bad Request message. I then set the Cookie Expiration on the AntiForgery options to 90 days. I was able to allow the page to sit for up to 6 hours and still login. However, after around 8 hours (overnight), I received the blank page again after attempting to login.

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login
services.AddAntiforgery(options =>
{
    options.Cookie.Expiration = TimeSpan.FromDays(90);
});

I expect to be able to sit on the login page for 90 days which is the duration of the cookie but that doesn't work. How do I get the cookie for the AntiforgeryToken to last the entire 90 days or whatever time I set it to and not timeout or expire? Is there a way to catch this error and redirect the user back to the login method?


Yet another implementation using the default one including all prechecks, logging etc. And it's still an AuthorizationFilter, so that prevents any further action execution. The only difference is that it triggers HttpGet to the same url instead of the default 400 response, a kind of the Post/Redirect/Get pattern implementation.

public class AnotherAntiForgeryTokenAttribute : TypeFilterAttribute
{
    public AnotherAntiForgeryTokenAttribute() : base(typeof(AnotherAntiforgeryFilter))
    {
    }
}


public class AnotherAntiforgeryFilter:ValidateAntiforgeryTokenAuthorizationFilter,
    IAsyncAuthorizationFilter
{
    public AnotherAntiforgeryFilter(IAntiforgery a, ILoggerFactory l) : base(a, l)
    {
    }

    async Task IAsyncAuthorizationFilter.OnAuthorizationAsync(
        AuthorizationFilterContext ctx)
    {
        await base.OnAuthorizationAsync(ctx);

        if (ctx.Result is IAntiforgeryValidationFailedResult)
        {
            // the next four rows are optional, just illustrating a way
            // to save some sensitive data such as initial query
            // the form has to support that
            var request = ctx.HttpContext.Request;
            var url = request.Path.ToUriComponent();
            if (request.Form?["ReturnUrl"].Count > 0)
                url = $"{url}?ReturnUrl={Uri.EscapeDataString(request.Form?["ReturnUrl"])}";

            // and the following is the only real customization
            ctx.Result = new LocalRedirectResult(url);
        }
    }
}

ValidateTokens exception on ASP.NET MVC Login - FIX, NET MVC Web Application form with the Anti-Forgery token feature on. we strongly recommend checking out the CSRF Wikipedia page,� In this article, we will try to understand Anti-forgery Token in ASP.NET MVC. Anti-forgery stands for “Act of copying or imitating things like a signature on a check, an official document to deceive the authority source for financial gains”. Now, in the case of web applications, it is termed as CSRF.


This was my final solution. I added a attribute using the IAntifogery dependency injection.

public class CustomValidationAttribute : ActionFilterAttribute
{
    private IAntiforgery _antiForgery { get; }

    public CustomValidationAttribute(IAntiforgery antiforgery)
    {
        _antiForgery = antiforgery;
    }

    public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        var isRequestValid = await this._antiForgery.IsRequestValidAsync(context.HttpContext);
        if (!isRequestValid)
        {
            //Add Code here if token is not valid

            return;         
        }

        await next();
    }
}

Add the attribute to your controller methods that also use [HttpPost]

[TypeFilter(typeof(CustomValidationAttribute))]

ASP.NET MVC Anti Forgery Token is not one-time (per request , NET Anti Forgery Token is per session, not per request (or POST request and so on). But token on the form changes (it's new) with every request (page refresh). cookie for your current user name and with an expiration time of 5 minutes. New cookies are sent and an empty session scope exists for your CFML to fill. Prevent Cross-Site Request Forgery (XSRF/CSRF) attacks in ASP.NET Core. 12/05/2019; 14 minutes to read +14; In this article. By Rick Anderson, Fiyaz Hasan, and Steve Smith. Cross-site request forgery (also known as XSRF or CSRF) is an attack against web-hosted apps whereby a malicious web app can influence the interaction between a client browser and a web app that trusts that browser.


Slight modification to d_f code https://stackoverflow.com/a/56383473/841898 Instead of page redirect we just add error to ModelState. Then we display in model state summary.

public class CustomAntiForgeryTokenAttribute : TypeFilterAttribute
{
    public CustomAntiForgeryTokenAttribute() : base(typeof(AnotherAntiforgeryFilter))
    {
    }
}


public class AnotherAntiforgeryFilter : ValidateAntiforgeryTokenAuthorizationFilter,
    IAsyncAuthorizationFilter
{
    public AnotherAntiforgeryFilter(IAntiforgery a, ILoggerFactory l) : base(a, l)
    {
    }

    async Task IAsyncAuthorizationFilter.OnAuthorizationAsync(
        AuthorizationFilterContext ctx)
    {
        await base.OnAuthorizationAsync(ctx);

        if (ctx.Result is IAntiforgeryValidationFailedResult)
        {
            ctx.ModelState.AddModelError("Token", "Validation Token Expired. Please try again");
            ctx.Result = null;

        }
    }
}

Troubleshooting anti-forgery token problems, antiforgery token has any expiration time, Tell me antiforgery token has any token is generated for the comment form but this token contains an empty username form field token do not match” on page with ViewModel and two forms 1 ASP. Preventing Cross-Site Request Forgery (CSRF) Attacks in ASP.NET MVC Application. 12/12/2012; 3 minutes to read +5; In this article. by Mike Wasson. Cross-Site Request Forgery (CSRF) is an attack where a malicious site sends a request to a vulnerable site where the user is currently logged in


ASP.NET MVC Anti-Forgery Token Issues, c# - Anti-forgery token issue (MVC 5) - Stack Overflow server tries to use the invalid identifier without redirecting the user to the log-in page and get the proper nameidentifier. logged in so the token will have an empty string for the username, after the user logs in, if you do NET MVC CSRF Anti-Forgery Tokens expire? Anti-forgery token is used to prevent CSRF (Cross-Site Request Forgery) attacks. Here is how it works in high-level: IIS server associates this token with current user’s identity before sending it to the client In the next client request, the server expects to see this token If the token is missing


ASP.Net Identity, It is easily reproduced with an empty MVC 5 project using ASP. user is authentication, if not, then redirect to login page (RedirectToAction). to /Account /LogOff fails the Anti-forgery token validation and throws an exception� The AntiForgeryToken html helper will generate a new one token for every form page requested and store it in a session cookie – you can therefore only have one antiforgery tokenised page open per domain as a second page will change the content of the validation token cookie and break all open pages but the last tab loaded.


Apparently Random Error: "Antiforgery token validation failed. The , Perhaps setting a MaxAge/Expiration for the cookie would help with this Both of those pages render a form with the anti-forgery token (e.g.� If this occurs, simply move your anti-forgery token inside the using statement, as seen in the sample below. It belongs inside the form tag on the page. The following is an example of a Razor view for a form that contains a name and email field. The only additional magic here is to add the line containing @Html.AntiForgeryToken().