Angular2 ASP.NET Core AntiForgeryToken

后端 未结 4 2014
礼貌的吻别
礼貌的吻别 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 17:14

    I am using a action filter to send the request tokens. Simply apply it to the actions you want a new antiforgery token, e.g. Angular2 SPA, WebAPI action, etc.

    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
    public class AngularAntiForgeryTokenAttribute : ActionFilterAttribute
    {
        private const string CookieName = "XSRF-TOKEN";
        private readonly IAntiforgery antiforgery;
    
        public AngularAntiForgeryTokenAttribute(IAntiforgery antiforgery)
        {
            this.antiforgery = antiforgery;
        }
    
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            base.OnResultExecuting(context);
    
            if (!context.Cancel)
            {
                var tokens = antiforgery.GetAndStoreTokens(context.HttpContext);
    
                context.HttpContext.Response.Cookies.Append(
                    CookieName,
                    tokens.RequestToken,
                    new CookieOptions { HttpOnly = false });
            }
        }
    }
    
    /* HomeController */
    
    [ServiceFilter(typeof(AngularAntiForgeryTokenAttribute), IsReusable = true)]
    public IActionResult Index()
    {
        return View();
    }
    
    /* AccountController */
    
    [HttpPost()]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    // Send new antiforgery token
    [ServiceFilter(typeof(AngularAntiForgeryTokenAttribute), IsReusable = true)]
    public async Task Register([FromBody] RegisterViewModel model)
    {
        //...
        return Json(new { }); 
    }
    

    Register the attribute in Startup, and configure Antiforgery service to read the request token form "X-XSRF-TOKEN" header.

    public class Startup
    {
        // ...
    
        public void ConfigureServices(IServiceCollection services)
        {
            // ...
    
            services.AddScoped();
            services.AddAntiforgery(options =>
            {
                options.HeaderName = "X-XSRF-TOKEN";
            });
        }
    }
    

提交回复
热议问题