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

前端 未结 3 1151
傲寒
傲寒 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.

提交回复
热议问题