how to implement csrf protection for cross domain requests

后端 未结 3 1930
耶瑟儿~
耶瑟儿~ 2021-01-31 10:30

I have two web apps, one for the Web UI in AngularJS and one for the REST webservices in Java. Both are deployed on separate domains.

The applications uses cookie for au

3条回答
  •  情书的邮戳
    2021-01-31 11:18

    You were on the right track with this:

    I also tried to implement the creation of the csrf cookie on the Web UI itself in the browser but the browser does not send the cookie to the webservice as its in different domain.

    The CSRF cookie isn't meant to be "sent" to the server, it is meant to be read by the client and then supplied in a custom HTTP request header. Forged GET requests (triggered by HTML tags such as ) from other domains cannot set custom headers, so this is how you assert that the request is coming from a javascript client on your domain.

    Here is how you can implement the idea you were working on, imagine you have api.domain.com and ui.domain.com:

    1) User loads the Angular client from ui.domain.com

    2) User posts authentication information from Angular client to api.domain.com

    2) Sever replies with an HttpOnly authentication cookie, called authCookie, and a custom header e.g. X-Auth-Cookie, where the value of this header is a unique value that is linked to the session that is identified by the authCookie

    3) The Angular client reads the X-Auth-Cookie header value and stores that value in a XSRF-TOKEN cookie on its domain, ui.domain.com

    • So now you have:

      • XSRF-TOKEN cookie on ui.domain.com
      • authCookie cookie on api.domain.com

    4) User makes a request of a protected resource on api.domain.com. The browser will automatically supply the authCookie value, and Angular will automatically send the X-XSRF-TOKEN header, and will send the value that it reads from the XSRF-TOKEN cookie

    5) Your server asserts that the value of X-XSRF-TOKEN is linked to the same session that is identified by the value of the authCookie

    I hope this helps! I've also written about token authentication for Angular, Token Based Authentication for Single Page Apps (SPAs) (Disclaimer: I work at at Stormpath)

提交回复
热议问题