如何使用angular2应用程序和net core应用程序实现X-XSRF-TOKEN?

ame*_*els 5 c# angularjs asp.net-core angular

我在Startup.cs中设置了我的净核心应用程序和防伪Middlweare:

        services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
Run Code Online (Sandbox Code Playgroud)

在ConfigureServices方法中

        app.UseAntiForgeryMiddleware();
Run Code Online (Sandbox Code Playgroud)

在配置方法中。

反伪造中间件:

public class AntiForgeryMiddleware
    {
        private readonly IAntiforgery antiforgery;
        private readonly AntiforgeryOptions options;
        private readonly RequestDelegate next;

        public AntiForgeryMiddleware(RequestDelegate next, IAntiforgery antiforgery, IOptions<AntiforgeryOptions> options)
        {
            this.next = next;
            this.antiforgery = antiforgery;
            this.options = options.Value;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                if (string.Equals(context.Request.Path.Value, "/", StringComparison.OrdinalIgnoreCase) ||
                    string.Equals(context.Request.Path.Value, "/index.html", StringComparison.OrdinalIgnoreCase))
                {
                    // We can 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 });
                }

                if (string.Equals("POST", context.Request.Method, StringComparison.OrdinalIgnoreCase))
                {
                    await antiforgery.ValidateRequestAsync(context);

                    context.Response.StatusCode = 204;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            await next(context);
        }
    }
Run Code Online (Sandbox Code Playgroud)

我用

[ValidateAntiForgeryToken]
Run Code Online (Sandbox Code Playgroud)

在我的控制器动作上

如何设置angular2发布请求以发送与网络核心应用匹配的x-xsrf-token标头?

Mar*_*vic 1

您所说的是将标头插入x-xsrf-token到您的请求中并将其发送到后端。

您可以通过在进行 http 调用时修改标头选项来实现此目的:

服务

@Injectable
export class YourService {

    constructor(private http: Http) { }

    makeSomeRequst(data: any) {

        let headers = new Headers({ 'X-XSRF-TOKEN': yourTokenFromLocalStorage });
        let options = new RequestOptions({ headers: headers });

        this.http.post('url to your API call', data, options)
            .subscribe(result => {
                console.log('Your request was done and compliant to security on backend');
            }, err => {
                console.error('There was a problem with authentication');
                console.log(err)
            });
    }

}
Run Code Online (Sandbox Code Playgroud)

这样,您将修改标头并插入令牌以符合您的安全机制。如果您想使其自动化,您可以按照本教程了解如何为 http 调用创建拦截器并在一个位置为所有这些调用插入令牌,而不是在每个服务中手动执行此操作:

您需要扩展 Angular 的 Http 并向您的模块提供新的依赖项。请按照此处的完整教程进行操作:

https://medium.com/aviabird/http-interceptor-angular2-way-e57dc2842462