微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 如何使用angular2 app和net core app实现X-XSRF-TOKEN?

我在Startup.cs中设置了我的net core app和antiforgery middlweare:

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

在ConfigureServices方法中,和

        app.UseAntiForgeryMiddleware();

在Configure方法中.

防伪中间件:

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);
        }
    }

我用

[ValidateAntiForgeryToken]

在我的控制器动作上.

如何设置angular2 post请求以发送符合net core app的x-xsrf-token标头?

解决方法:

您所说的是将标头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)
            });
    }

}

有了这个,您将修改标头和插入标记以符合您的安全机制.如果要自动化,可以按照本教程学习如何为http调用创建拦截器,并在一个地方为所有这些调用插入令牌,而不是在每个服务中手动执行:

您需要扩展Angular的Http并为您的模块提供新的依赖项.
按照完整的教程:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐