Angular 6 and AutoValidateAntiforgeryToken

╄→尐↘猪︶ㄣ 提交于 2020-07-10 08:07:20

问题


I have searched a lot but i don't find how to implement the AutoValidateAntiforgeryToken.
I'm creating an Angular 6 spa with TypeScript, connecting to an endpoint .NET Core 2.1
In ConfigureServices added

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

before AddMvc() added in Configure

app.Use(next => context =>
{
    string path = context.Request.Path.Value;
    if (string.Equals(path, "/", StringComparison.OrdinalIgnoreCase) || string.Equals(path, "/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 });
    }
    return next(context);
});

The Angular documentation is not clear, if i understood well i should read a cookie named X-XSRF-TOKEN and transmit back in the http call as header: but i try to read this cookie in angular (using ngx-cookie-service, with a code as this.cookieSvc.get("X-XSRF-TOKEN")) this cookie is empty.
If someone could help, thanks.


回答1:


For your issue, check points below to understand your issue better.

  1. For CookieXSRFStrategy, it configure XSRF-TOKEN as cookie name and X-XSRF-TOKEN as header Name for XSRF.
  2. To correspond to Angular, Asp.Net Core work with this convention just like you done.

    • Configure your app to provide a token in a cookie called XSRF-TOKEN

    • Configure the antiforgery service to look for a header named X-XSRF-TOKEN.

So, if you want to get AntiforgeryToken from Angular site, try query cookies by XSRF-TOKEN.



来源:https://stackoverflow.com/questions/52405972/angular-6-and-autovalidateantiforgerytoken

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!