Bruno Finger Bruno Finger - 7 days ago 6
AngularJS Question

Why can't I get the vaue of __RequestVerificationToken from AngularJS or even pure JavaScript?

I am writing a front-end application with Bootstrap and AngularJS for a C# MVC back-end code.

Using Chrome's developer console (and any other browser, including IE), I can see a cookie called

__RequestVerificationToken
, as the image below shows:

enter image description here

I understand this is a technique used to prevent CSRF attacks. Anyway, since this cookie is there, I was trying to get it's value using AngluarJS module
$cookies
, but it always returns
undefined
, and printing
document.cookie
doesn't show it. Below is the code used:

...
this.initApp = function () {
console.log('Value of __RequestVerificationToken: "' + $cookies.__RequestVerificationToken + '"'); // Angular way
console.log('Cookie: "' + document.cookie + '"'); // Pure JavaScript
};
...


So my question is, why can't I get its value if the cookie is there and is being sent to the client in every single response, and how do I get its value?

Answer

You have [ValidateAntiForgeryToken] attribute that writes a unique value to an HTTP-only cookie before your action. You also should add @Html.AntiForgeryToken() in your form and the same value is written to the form as a hidden field.

var token = $('input[name="__RequestVerificationToken"]').val();
Comments