We have some existing MVC web services that are called AJAX style from web pages. These services make use of the ValidateAntiForgeryToken attribute to help prevent request forgeries.
We are looking to migrate these services to Web API, but there appears to be no equivalent anti-forgery functionality.
Am I missing something? Is there a different approach to addressing request forgeries with Web API?
After thinking about this some more, it is a bad idea to mix the cookie and the form tokens since it defeats the whole purpose of the anti forgery token. It is better to keep the cookie part as a cookie while moving the form part to an auth header, therefore this new answer (again as an AuthorizeAttribute).
Then just decorate your controller or methods with [ApiValidateAntiForgeryToken]
And add to the razor file this to generate your token for javascript:
Oswaldo's answer but implemented as an AuthorizeAttribute
You can decorate your controller or methods with [ApiValidateAntiForgeryToken] and then pass RequestVerificationToken: "@ApiValidateAntiForgeryToken.GenerateAntiForgeryTokenForHeader()" as a header for the method in your razor javascript code.
You could implement such authorization attribute:
and then decorate your API actions with it:
Complementing Above code FilterAttribute
Html Function Using Razor
Using Angular
This link helped, you can retrieve the anti-forgery token from the razor view and pass the token as a header: