ValidateAntiForgeryToken in an ASP.NET Core React SPA Application

后端 未结 1 375
感情败类
感情败类 2020-12-15 12:33

I\'m trying to use the framework\'s tools to add some simple CSRF validation to an ASP.NET Core React SPA. The application itself is essentially a create-react-app setup (a

相关标签:
1条回答
  • 2020-12-15 13:07

    I just inspect the log and find out there's an exception:

    Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The required antiforgery cookie ".AspNetCore.Antiforgery.HPE6W9qucDc" is not present. at Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgery.ValidateRequestAsync(HttpContext httpContext) at Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ValidateAntiforgeryTokenAuthorizationFilter.OnAuthorizationAsync(AuthorizationFilterContext context)

    It indicates that you forgot to configure the cookie name :

       public void ConfigureServices(IServiceCollection services)
       {
           //services.AddAntiforgery();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    
           // In production, the React files will be served from this directory
           services.AddSpaStaticFiles(configuration =>
           {
               configuration.RootPath = "ClientApp/build";
           });
       }
    

    So I just add a configuration as below :

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAntiforgery(o => {
                o.Cookie.Name = "X-CSRF-TOKEN";
            });
            // ...
        }
    

    and it works now.

    Also, if you would like to omit the line of services.AddAntiforgery(options => options.Cookie.Name = "X-CSRF-TOKEN"); , you can use the built-in antiforgery.GetAndStoreTokens(context) method to send cookie:

       app.Use(next => context =>
        {
            if (context.Request.Path == "/")
            {
                //var tokens = antiforgery.GetTokens(context);
                var tokens = antiforgery.GetAndStoreTokens(context);
                context.Response.Cookies.Append("X-CSRF-TOKEN", tokens.CookieToken, new CookieOptions { HttpOnly = false });
                context.Response.Cookies.Append("X-CSRF-FORM-TOKEN", tokens.RequestToken, new CookieOptions { HttpOnly = false });
            }
            return next(context);
        })
    

    Both should work as expected.

    0 讨论(0)
提交回复
热议问题