Mikael Egnér
Mikael Egnér

Reputation: 23

Problem with Validate Anti Forgery

I have a problem regarding MVC Anti forgery token. When I do my authentication I have pseudo code like this:

var user = userRepository.GetByEmail(email);
System.Threading.Thread.CurrentPrincipal = HttpContext.Current.User = user;

by doing so I'm able to get the current user in my code like this:

var user = HttpContext.Current.User as EntityUser;

This works fine until I add the [ValidateAntiForgeryToken] attribute to an action. When I add the attribute I get

A required anti-forgery token was not supplied or was invalid.

If I comment out this line:

System.Threading.Thread.CurrentPrincipal = HttpContext.Current.User = user;

The antiforgery validation works fine, but the I don't have my convenient way of getting my "EntityUser" from the HttpContext. Any ideas of how to work around this? Best regards Mikael

Upvotes: 0

Views: 1463

Answers (2)

Erdogan Kurtur
Erdogan Kurtur

Reputation: 3685

Actually AntiForgeryToken uses HttpContextBase.User in validation. See AntiForgeryWorker.Validate

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039548

I don't think that those are related. When you add the [ValidateAntiForgeryToken] attribute to your controller action you also need to add the hidden field inside your form:

<%= Html.AntiForgeryToken() %>

If you are submitting it through AJAX you always need to send this token along the request.

Upvotes: 3

Related Questions