asp.net核心1.1防伪与角2/4

时间:2017-05-20 02:58:56

标签: .net angular security core

我正在尝试使用angurl 2/4 cli在asp.net core 1.1上实现防伪令牌,但每当我使用" ValidateAntiForgeryToken"系统给我400错误请求错误。

在asp.net startup.cs中我使用

services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");



app.Use(async (context, next) =>{
 await next();
 string path = context.Request.Path.Value;
 if (path != null && !path.ToLower().Contains("/api"))
 {
      var tokens = antiforgery.GetAndStoreTokens(context);
      context.Response.Cookies.Append("XSRF-TOKEN",
       tokens.RequestToken, new CookieOptions{HttpOnly = false});
 }

 if (context.Response.StatusCode == 404 && 
     !Path.HasExtension(context.Request.Path.Value))
 {
     context.Request.Path = "/index.html";
     context.Response.StatusCode = 200;
     await next();
 }

});

在角度app.module.ts我使用类似

的东西
provider:[{ provide: XSRFStrategy, useFactory: xsrfFactory}],

export function xsrfFactory() {
    return new CookieXSRFStrategy('*******', '********');
}

1 个答案:

答案 0 :(得分:0)

本指南有用吗? http://www.dotnetcurry.com/aspnet/1343/aspnet-core-csrf-antiforgery-token

public class AngularAntiforgeryCookieResultFilter: ResultFilterAttribute
{
    private IAntiforgery antiforgery;
    public AngularAntiforgeryCookieResultFilter(IAntiforgery antiforgery)
    {
        this.antiforgery = antiforgery;
    }

    public override void OnResultExecuting(ResultExecutingContext context)
    {
        if (context.Result is ViewResult)
        {
            var tokens = antiforgery.GetAndStoreTokens(context.HttpContext);
            context.HttpContext.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions() { HttpOnly = false });
        }
    }
}

services.AddAntiforgery(opts => opts.HeaderName = "X-XSRF-Token");
services.AddMvc(opts =>
{
    opts.Filters.AddService(typeof(AngularAntiforgeryCookieResultFilter));
});
services.AddTransient< AngularAntiforgeryCookieResultFilter >();