Search code examples
asp.net-mvcangularjsangularjs-scopeantiforgerytokencsrf-protection

Pass RequestVerificationToken from Angular js to mvc controller


I want to pass a RequestVerificationToken in my home page to the controller actions which are decorated with ValidateAntiforgeryToken attribute.

My base view is as below:

@{
    Layout = null;
}
@Html.AntiForgeryToken()

The token rendered in html as:

<input name="__RequestVerificationToken" type="hidden" value="9DLRgZ1UYKCRdDxhIx0qJ9fovUJafQ8tvfkd21M6hJHQBRnbvNLu5BlYwZXwGUUXmkGfmB5cFMsgaH0rbd7OorW9WVC3XvQYGdbki3KoxMaYxfEf7FLELnm3IDF95bjET83Dls1ZnLNAoLxFO_2SbPkwg7lJjKF6F4vPWredPYM1" class="ng-scope">

I'm trying to pass the token in httpExecute function as shown:

this.httpExecute = function (opt) {
$http.defaults.headers.common['_RequestVerificationToken'] = $(':input:hidden[name*="RequestVerificationToken"]').val();        
    return $http({
        method: opt.method,
        url: opt.url,
        params: opt.params,
        data: opt.data
    })
     .error(function (response) {
         if (response.IsTokenExpired == true) {
             $user.logoutsession();
         }
     });
}

But I'm getting the token value as null/undefined. What am I doing wrong here? Please help. Thanks


Solution

  • Yes, I'm getting it correctly, if I pass it like below:

    return $http({
            method: opt.method,
            url: opt.url,
            params: opt.params,
            data: opt.data,
            headers: {
                '__RequestVerificationToken': $(':input:hidden[name*="RequestVerificationToken"]').val()
            }
        })