Angular2 ASP.NET Core AntiForgeryToken

后端 未结 4 2021
礼貌的吻别
礼貌的吻别 2020-12-13 16:19

I have an Angular2 app. It is running within ASP.NET 5 (Core).
It makes Http calls to the controller which is working fine.

Bu

4条回答
  •  孤城傲影
    2020-12-13 16:50

    A custom action filter is not necessary. It can all be wired up in Startup.cs.

    using Microsoft.AspNetCore.Antiforgery;
    
    (...)
    
    public void ConfigureServices(IServiceCollection services)
    {
      services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
    
      (...)
    }
    
    public void Configure(IApplicationBuilder app, IAntiforgery antiforgery)
    {
      app.Use(next => context =>
      {
        if (context.Request.Path == "/")
        {
          //send the request token as a JavaScript-readable cookie, and Angular will use it by default
          var tokens = antiforgery.GetAndStoreTokens(context);
          context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions { HttpOnly = false });
        }
        return next(context);
      });
    
      (...)
    }
    

    Then all you need in your controllers is the [ValidateAntiForgeryToken] decorator wherever you want to enforce that a token is provided.

    For reference, I found this solution here - AspNet AntiForgery Github Issue 29.

提交回复
热议问题