blazor - How to make an handler for invalid forgery token? - Stack Overflow

admin2025-04-17  1

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

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

Share Improve this question edited Jan 31 at 22:11 marc_s 756k184 gold badges1.4k silver badges1.5k bronze badges asked Jan 31 at 9:47 impesigiuseppeimpesigiuseppe 133 bronze badges 3
  • Hello, what have you tried on your side ? This is quite standard mechanism of request handling so we can assume Microsoft already gives a lot of advices and examples to implement it. – AFract Commented Jan 31 at 9:50
  • Hello @AFract, thanks for the attention. I updated the question with the solution i tried to implement. – impesigiuseppe Commented Jan 31 at 15:03
  • Your update have nothing to do with antiforgery validation – AFract Commented Jan 31 at 15:41
Add a comment  | 

1 Answer 1

Reset to default 1

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>();
转载请注明原文地址:http://www.anycun.com/QandA/1744870724a88791.html