-->

CSRF validation needed or not when using RESTful A

2019-01-29 02:09发布

问题:

The following is written on the of the page of FOSRestBundle:

"CSRF validation

When building a single application that should handle forms both via HTML forms as well as via a REST API, one runs into a problem with CSRF token validation. In most cases it is necessary to enable them for HTML forms, but it makes no sense to use them for a REST API. For this reason there is a form extension to disable CSRF validation for users with a specific role. This of course requires that REST API users authenticate themselves and get a special role assigned."

https://github.com/FriendsOfSymfony/FOSRestBundle/blob/master/Resources/doc/2-the-view-layer.md#csrf-validation

Is this explanation correct? Could you explain why it's correct?

Thank you!

回答1:

CSRF token validation is not actually used for implementing RESTful Web Services, because it violates the initial principles of REST (REST is stateless, there is no client context, being saved on the server side). Instead one can check the Referer Header (it does not require a per-user state) and maybe some combination of custom header field and GET parameter. If your API is not public, then you should use an API-key based authentication or OAuth.