impesigiuseppe
impesigiuseppe

Reputation: 13

How to make an handler for invalid forgery token?

Is there a way to handle invalid forgery token error in Blazor WebApp .NET 8 ?

A valid antiforgery token was not provided with the request. Add an antiforgery token, or disable antiforgery validation for this endpoint

Like a redirection or something else

UPDATE

I tried this in my Program.cs:

app.Use(async (context, next) =>
{
    await next();

    if (context.Response.StatusCode == 404 && !context.Response.HasStarted)
    {
        context.Response.Redirect("./404");
    }

    if (context.Response.StatusCode == 400 && !context.Response.HasStarted)
    {
        context.Response.Redirect("./400");
    }
});

It should be redirect to /400 page

Upvotes: 1

Views: 30

Answers (1)

Qiang Fu
Qiang Fu

Reputation: 8411

The antiforgery validation error is not an exception that can be caught in middleware directly because ASP.NET Core handles it before the request reaches middleware. A workaround is you could make a middleware to do antiforery validation earlier and redirect.

    public class AntiforgeryValidationMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly IAntiforgery _antiforgery;
        private readonly ILogger<AntiforgeryValidationMiddleware> _logger;

        public AntiforgeryValidationMiddleware(RequestDelegate next, IAntiforgery antiforgery, ILogger<AntiforgeryValidationMiddleware> logger)
        {
            _next = next;
            _antiforgery = antiforgery;
            _logger = logger;
        }

        public async Task Invoke(HttpContext context)
        {
            // Apply antiforgery validation only to unsafe methods (POST, PUT, DELETE)
            if (HttpMethods.IsPost(context.Request.Method) ||
                HttpMethods.IsPut(context.Request.Method) ||
                HttpMethods.IsDelete(context.Request.Method))
            {
                try
                {
                    await _antiforgery.ValidateRequestAsync(context);
                }
                catch (AntiforgeryValidationException ex)
                {
                    _logger.LogWarning("Antiforgery token validation failed: {Message}", ex.Message);
                    context.Response.Redirect("./404");
                    return;
                }
            }

            await _next(context);
        }
    }

Add the middleware

var app = builder.Build();
app.UseMiddleware<AntiforgeryValidationMiddleware>();

Upvotes: 0

Related Questions