Validating AntiForgery token globally in ASP.NET Core

1.5k views Asked by At

I want to validate AntiForgery token in ASP.NET Core application. I know i can individually do that by adding [AutoValidateAntiforgeryToken] or [ValidateAntiforgeryToken] attributes on Action methods as suggested in SO post here

I'm looking for global approach to validate token for all POST methods. So i created a middleware to do so. However i could not find suitable method to validate the token. Like in classic asp.net there is AntiForgery.Validate(). What's the equivalent method in ASP.NET Core

public class ValidateAntiForgeryTokenMiddleware
{
    private readonly RequestDelegate _next;

    public ValidateAntiForgeryTokenMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext httpContext)
    {
        if (httpContext.Request.Method.ToUpper() == "POST")
        {
            // where does this mehod exists?
            // i could not find it in Microsoft.AspNetCore.Antiforgery namespace
            AntiForgery.Validate();
        }

        await _next(httpContext);
    }
}

public static class ValidateAntiForgeryTokenMiddlewareExtensions
{
    public static IApplicationBuilder UseValidateAntiForgeryToken(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<ValidateAntiForgeryTokenMiddleware>();
    }
}
1

There are 1 answers

0
LP13 On BEST ANSWER

I have to Inject Antiforgery as service

public class ValidateAntiForgeryTokenMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IAntiforgery _antiforgery;

    public ValidateAntiForgeryTokenMiddleware(RequestDelegate next, IAntiforgery antiforgery)
    {
        _next = next;
        _antiforgery = antiforgery;
    }

    public async Task Invoke(HttpContext httpContext)
    {
        if (httpContext.Request.Method.ToUpper() == "POST")
        {
            await _antiforgery.ValidateRequestAsync(httpContext);
        }

        await _next(httpContext);
    }
}

add Antiforgery as service in startup.cs

   public void ConfigureServices(IServiceCollection services)
   {       
        services.AddAntiforgery();
   }

Use my middlware

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime)
    {
        app.UseValidateAntiForgeryToken();

   }