28

How does Angular (2) handle XSS and CSRF. Does it even handle these attacks? If so, what do I have to do to use this protection? If not, do I have to handle all these attacks in my server, or somehow with TypeScript in the frontend?

I have read that you have to use "withCredentials: true", but I'm not quite sure where to put this code or if it is even that, what I'm looking for.

In the https://angular.io/ webpage I didn't find anything about this (or I just missed it).

Raedwald
  • 46,613
  • 43
  • 151
  • 237
TheHeroOfTime
  • 751
  • 4
  • 9
  • 23

3 Answers3

41

Angular2 provides built-in, enabled by default*, anti XSS and CSRF/XSRF protection.

The DomSanitizationService takes care of removing the dangerous bits in order to prevent an XSS attack.

The CookieXSRFStrategy class (within the XHRConnection class) takes care of preventing CSRF/XSRF attacks.

*Note that the CSRF/XSRF protection is enabled by default on the client but only works if the backend sets a cookie named XSRF-TOKEN with a random value when the user authenticates. For more information read up about the Cookie-to-Header Token pattern.

UPDATE: Official Angular2 security documentation: https://angular.io/docs/ts/latest/guide/security.html (Thanks to Martin Probst for the edit suggestion!).

Daniel Gartmann
  • 11,678
  • 12
  • 45
  • 60
  • Worth looking at that security guide as a whole, but also ref https://angular.io/guide/http#security-xsrf-protection specifically (which the security guide links to) – jmq Jan 22 '18 at 18:16
3

For mentioned server side in Angular, the CSRF you might handle using Express:

app.use(express.csrf())
app.use(function (req, res, next) {
  res.cookie('XSRF-TOKEN', req.session._csrf);
  res.locals.csrftoken = req.session._csrf;
  next();
})

Not sure if with the new HttpClientXsrfModule it's still required though. It might be enough to add only the following (but need to be confirmed) on the client side in app.module:

HttpClientXsrfModule.withOptions({
  cookieName: 'XSRF-TOKEN',
  headerName: 'X-XSRF-TOKEN'
})
Daniel Danielecki
  • 8,508
  • 6
  • 68
  • 94
0

Following is brief guide on how CSRF is handled in backend/server-side implementation when using SpringBoot

The token in CSRF can be associated either with HttpSession or in a cookie

To handle as a cookie, we may pass

.csrfTokenRepository(new CookieCsrfTokenRepository())

To handle as a HttpSession, we may pass

.csrfTokenRepository(new HttpSessionCsrfTokenRepository())   

Even we can have a custom csrf token repository by implmenting CsrfTokenRepository in case we need skip specific url and so on

all above can be used when overriding configure method of WebSecurityConfigurerAdapter

SNL
  • 79
  • 1
  • 4