How to prevent CSRF in a RESTful application?

前端 未结 6 485
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-12 12:07

Cross Site Request Forgery (CSRF) is typically prevent with one of the following methods:

  • Check referer - RESTful but unreliable
  • insert token into for
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-12 12:43

    You definitely need some state on the server to authenticate/authorize. It need not be the http session though, you could store it in a distributed cache (like memcached) or a database.

    If you use cookies for authentication, the easiest solution is to double-submit the cookie value. Before you submit the form, read the session id from the cookie, store it in a hidden field and then submit it. On the server side, confirm that the value in the request is the same as the session id (that you got from the cookie). Evil script from another domain will not be able to read the session id from the cookie, thus preventing CSRF.

    This scheme uses a single identifier across the session.

    If you want more protection, generate a unique id per-session per-form.

    Also, DO NOT generate tokens in JS. Anybody can copy the code and run it from a different domain to attack your site.

提交回复
热议问题