简体   繁体   中英

Handling Angular 2 csrf for cross origins

below is the architecture of our application.

  1. the web interface [the client] is standalone Angular 2 application [domain.com]
  2. the [proxy] which held the client credential [the web interface secret] [domain2.com]
  3. the [API] itself which has the auth server [domain3.com]

the application flow are like below:

  1. user enter his credential username+password into [the client] login page which then send it to the [proxy] .
  2. then proxy will append the credential to the request and forward it to the [API] .
  3. [API] will be able to obtain the access+refresh tokens after validating the user credential & return it to the [proxy]
  4. [proxy] return the response along with the header [Set-Cookie:XSRF-TOKEN]
  5. [client] should then able to read the [XSRF-TOKEN] & send it along with every request as [X-XSRF-TOKEN] header.

everything is working as expected both on the auth server, proxy & the client except for step 5:

Angular should be able to handle this automatically as per the documentation

{ provide: XSRFStrategy, useValue: new CookieXSRFStrategy('XSRF-TOKEN', 'X-CSRF-TOKEN')}

where is angular will be able to get the value of the [XSRF-TOKEN] cookie and create the [X-CSRF-TOKEN] header along with every request we made through the application.

although & as I building the architecture using different origins, angular could not be able to read cookie from another origin.

The problem with this approach I am facing is that since the server is in different domain, I cannot read the cookie through XSRFStrategy provider. Is there a way to read a value of that cookie?

If not, so the current architecture is wrong & I need to build the [client] & [proxy] in the same domain which I am avoided this approach because I need to separate the presentation layer from any backend code.

So, simply my question is how to implement csrf protection for this kind of situation?

In your port you mention "access+refresh tokens", which sounds like you'd be using OAuth. In a cross-origin scenario, CSRF is often simply not an issue. If there is any kind of HTTP Header your client needs to send to authenticate, you can safely disable CSRF.

A CSRF attack would make your browser send cookie stored for the [API] domain, and with some hacks the attacker might also send a "X-Requested-With: XMLHttpRequest". But if your API also needs a "Authorization: Bearer ..." token, you can drop the whole CSRF nuisance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM