I am developing a Web Application using Angular JS and ASP.NET MVC. I am having a problem with validating CSRF token. I asked a question dealing with CSRF token and AngularJS as well. But this question a little bit different. I am following this link now - http://techbrij.com/angularjs-antiforgerytoken-asp-net-mvc.
I created a Custom CSRF validation class like this
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class AngularValidateAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
{
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);
}
public void OnAuthorization(AuthorizationContext filterContext)
{
try
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
ValidateRequestHeader(filterContext.HttpContext.Request);
}
else
{
AntiForgery.Validate();
}
}
catch (HttpAntiForgeryException e)
{
throw new HttpAntiForgeryException("Anti forgery token cookie not found"); // This line is throwing error
}
}
}
Then I post like this in AngularJS:
$http({
method: 'POST',
url: path,
data: { Email : $scope.email, Password : $scope.password },
headers: {
'RequestVerificationToken': $rootScope.csrfToken
}
}).success(function (data, status, headers, config) {
alert('success')
}).error(function (data, status, headers, config) {
alert('error')
});
It always throws this error
I commented in the code above where error is throwing. What is wrong with my code?
