AngularJS can't find XSRF-TOKEN cookie
Asked Answered
S

1

2

I'm using angular 1.0.4 with an ASP.NET MVC4 + Web API project. I'm trying to leverage angular's CSRF protection to no avail. I can see that I'm passing along a cookie named XSRF-TOKEN, but when angular tries to add the value as a header named X-XSRF-TOKEN in the response, the value appears as undefined. I tried following the advice here, but the HTML has yet to render, so no element is found.

What might I be missing? Is the RequestVerificationToken cookie generated by ASP.NET MVC protected from javascript access?

Also, is it possible to have angular lazily retrieve either the cookie or form input value? If so, how? I cannot find any docs on how to do this.

Susette answered 16/3, 2013 at 2:5 Comment(5)
You can easily check if your cookie is httpOnly by taking a look at Resource tab in your Chrome Developer tools (Chrome console). Your cookie is httpOnly, and thus not accessible by JavaScript if 'http' column in Chrome console is set to 'Yes'.Snap
@Stewie: Thanks; however, the HTTP column is empty.Susette
Than that answers one of your questions: Your token cookie IS accessible in JavaScript.Snap
Well ... that's just weird. I wonder why the script doesn't find the cookie. Perhaps the cookie is only sent later, after the startup script is run. Either way, I've now worked around the issue. Thanks for your help, @Stewie.Susette
Not really an answer, but I've just posted [a question][1] with my approach to CSRF with Angular and ASP.NET WebAPI. Angular is happily picking up the cookie & setting it in the request header. You might be able to glean something from my code. [1]: https://mcmap.net/q/277428/-angular-against-asp-net-webapi-implement-csrf-on-the-server/84898See
S
1

I could not find an exact answer to my question. I ended up creating a service to find the 'input[name="__RequestVerificationToken"]', get its value, and return an object with that value. I then set the headers in the config using that object. This lets me lazily extract and append the value as a header for a form that doesn't appear immediately on the page.

I also realized, upon further review, that ASP.NET's AntiForgeryToken support requires both the cookie and form input/header value to validate, so the built-in AngularJS support wouldn't suffice anyway.

If anyone has a better solution, I will happily transfer the answer to that solution.

Susette answered 19/3, 2013 at 19:37 Comment(1)
I´m in a very similar situation can you post your service or can you help me with this #18093049Highlands

© 2022 - 2024 — McMap. All rights reserved.