I'm trying to implement CSRF using AntiForgeryToken from .Net Framework on a single page application. I've implemented some code inside my .csthml file and i've created an AuthorizeAttribute:
Index.cshtml
<script>
@functions{
public string GetAntiForgeryToken()
{
string cookieToken, formToken;
System.Web.Helpers.AntiForgery.GetTokens(null, out cookieToken, out formToken);
return cookieToken + ":" + formToken;
}
}
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
var xxx = '@GetAntiForgeryToken()';
jqXHR.setRequestHeader("X-CSRF", xxx);
});
</script>
ValidateHttpAntiForgeryTokenAttribute.cs
public class ValidateHttpAntiForgeryTokenAttribute : AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext actionContext)
{
var headers = actionContext.Request.Headers;
var headerToken = headers.Contains("X-CSRF") ? headers.GetValues("X-CSRF").FirstOrDefault() : null;
if (headerToken == null)
{
return false;
}
var tokenValues = headerToken.Split(':');
if (tokenValues.Length < 2)
{
return false;
}
else
{
var cookieToken = tokenValues[0];
var formToken = tokenValues[1];
try
{
AntiForgery.Validate(cookieToken, formToken);
}
catch(Exception ex)
{
return false;
}
}
return base.IsAuthorized(actionContext);
}
}
MyController.cs
[HttpGet]
[ValidateHttpAntiForgeryTokenAttribute]
public HttpResponseMessage Get()
{
...
}
Every time that ValidateHttpAntiForgeryTokenAttribute is called, i got the following error:
The provided anti-forgery token was meant for user "CMP\usr", but the current user is "dev@company.net"
I would like to know why it displays the username of computer instead the username that is logged on application and why the token isn't changing when call GetAntiForgeryToken() is executed.
Thank in advance.