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

前端 未结 3 1152
傲寒
傲寒 2021-02-01 10:01

I\'m trying to understand how I will be able to craft an API using ASP.NET Web API which will be protected from CSRF, while still being accessible from non-web environments (e.g

相关标签:
3条回答
  • 2021-02-01 10: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.

    0 讨论(0)
  • 2021-02-01 10:36

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

    0 讨论(0)
  • 2021-02-01 10:43

    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.

    0 讨论(0)
提交回复
热议问题