Home > Enterprise >  How to send AntiForgeryToken via AngularJs?
How to send AntiForgeryToken via AngularJs?

Time:09-16

In my MVC project I am calling method by AngularJs. I need to send the AntiForgeryToken to the method.

In view

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    ...
}

In MVC controller

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Model model)
{
  ...
}

In AngularJs controller

this.data.Name= $('#txtNm').val();
this.data.Id = $('#Id').val();
var token = angular.element("input[name='__RequestVerificationToken']").val();

$http({
method: "POST",
url: "/Students/Create",
dataType: 'json',
data: this.data,
headers: {
  '__RequestVerificationToken': token
 }
}).then(function (response) {
                //success
}, function (response) {
                //error
});

But, It's not working.

CodePudding user response:

try this

this.data.__RequestVerificationToken = $('input[name="`__RequestVerificationToken`"]').val();
.....

    data: this.data,
    dataType: 'JSON',
    contentType:'application/x-www-form-urlencoded; charset=utf-8',
.....

CodePudding user response:

1-CSHTML

The token are generated at the server by calling AntiForgery.GetTokens method.

<script>
            @functions{
        public string GetAntiForgeryToken()
        {
            string cookieToken, formToken;
            AntiForgery.GetTokens(null, out cookieToken, out formToken);
            return cookieToken   ":"   formToken;
        }


            }
    </script>

 @Html.AntiForgeryToken()
 <input name="RequestVerificationToken" data-ng-model="RequestVerificationToken" type="hidden" data-ng-init="RequestVerificationToken='@GetAntiForgeryToken()'" />

2-MVC Controller

When you process the request, extract the tokens from the request header. Then call the AntiForgery.Validate method to validate the tokens. The Validate method throws an exception if the tokens are not valid.

For Validate AntiForgeryToken I have used MyValidateAntiForgeryTokenAttribute().

[HttpPost]
        [MyValidateAntiForgeryTokenAttribute()]
        public ActionResult Create()
        {
            // Your students create logic will be here
        }

         [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
        public class MyValidateAntiForgeryTokenAttribute : FilterAttribute
        {
            private void ValidateRequestHeader(HttpRequestBase request)
            {
                string cookieToken = String.Empty;
                string formToken = String.Empty;
                string tokenValue = request.Headers["__RequestVerificationToken"];
                if (!String.IsNullOrEmpty(tokenValue))
                {
                    string[] tokens = tokenValue.Split(':');
                    if (tokens.Length == 2)
                    {
                        cookieToken = tokens[0].Trim();
                        formToken = tokens[1].Trim();
                    }
                }
                AntiForgery.Validate(cookieToken, formToken);
            }

3-Angular JS Controller

In http call assign in header $scope.RequestVerificationToken

        '__RequestVerificationToken': $scope.RequestVerificationToken
    }
  • Related