How does Angular handle XSS or CSRF?

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!).


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'
})