How does ValidateAntiForgeryToken fit with Web APIs that can be accessed via web or native app?

心不动则不痛 提交于 2019-12-02 18:34:36

CSRF only becomes a problem when you are using a persistent auth mechanism such as cookies, basic auth, NTLM etc. Mike Wasson has an example of using CSRF against webapi in Javascript - and I've seen versions in DelegatingHandlers ....

As CSRF is only a problem in web scenarios you can argue there's no real need to check for non-web requests. Every ajax request from a browser, whether via jquery, the native XmlHttpRequest classes or whatever comes with a header - X-Requested-With, which will have a value of XMLHttpRequest. So you could limit your CSRF checks to just requests with that header, as anything without it must have come from outside a browser.

Having said that if you are authenticating, I'd look at some sort of shared secret or OAuth mechanism, and have a DelegatingHandler server side to validate, and in the web app just put the token somewhere that it can be picked up via javascript and sent via an X-Authentication header - as it's not persistent and needs to be attached to every request (just like the CSRF token) there's no CSRF problems. Dominick, as ever, documents this sort of thing well.

Have a look at the SPA templates in the latest MVC4 update. They have a sample implementation for Anti-CSRF for Web API.

Take a look at the CORS implementation for WebAPI.

http://blogs.msdn.com/b/carlosfigueira/archive/2012/07/02/cors-support-in-asp-net-web-api-rc-version.aspx

Then you could allow only localhost as a valid URI on the webapi server. This would prevent other sites from loading attack code in the browser.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!