Search code examples
oauth-2.0csrfcsrf-protection

Why is OAuth a viable technique to prevent CSRF for RESTful APIs?


I have an exact situation with this question: What are some viable techniques for combining csrf protection with RESTful APIs?

One answer given talks about using

  • basic authentication with SSL
  • 1 API key per application
  • OAuth

I am already convinced about implementing OAuth2.0 where you will have access_token, client_id, client_secret for each app.

However, I was not aware that this would actually help prevent CSRF.

My opinion is that at the end of the day, you still need ssl.

Because in OAuth2.0, when the client app sends requests on behalf of the Resource Owner, they need to send alongside the data parameters such as client_id, client_secret and access token.

Without HTTPS, if the client_id, client_secret and access token are known either through leaks or man-in-the-middle, then there is still a chance of CSRF, albeit a small one because of the expiry period of the access token.

Is my understanding correct?


Solution

  • If a resource is protected by OAuth 2 alone and an attacker gets client_id, client_secret and an access token, then no CSRF is needed at all. The attacker directly can send a request to use the protected resource and will be served because OAuth 2 does not filter the source of the request, it requires an access token only.

    In general, you should definitely use HTTPS both for the authentication server and the protected resource to avoid man-in-the-middle attacks. However, if you're using the "authorization code grant" scenario (i.e. use it from your own web application), then the access token is not known even to the resource owner, he can intercept the authorization code only. Thus, if your web application has a trusted (e.g. intranet) connection to both the authorization server and the protected resource, it is safe to use an unencrypted connection to the protected resource.