Blog>
Snippets

Protecting against XSRF in Angular Universal

Detail a method to implement XSRF protection in server-side rendered Angular applications using Angular Universal.
import { XSRFStrategy, CookieXSRFStrategy } from '@angular/http';

export function xsrfFactory() {
  return new CookieXSRFStrategy('XSRF-TOKEN', 'X-XSRF-TOKEN');
}

// In your server module
import { NgModule } from '@angular/core';
import { ServerModule } from '@angular/platform-server';
import { AppModule } from './app.module';
import { ServerAppModule } from './app.server.module';

@NgModule({
  imports: [
    // The AppServerModule should import your AppModule followed
    // by the ServerModule from '@angular/platform-server'.
    AppModule,
    ServerModule
  ],
  providers: [
    // Register xsrfFactory to provide the CookieXSRFStrategy with custom cookie and header names.
    { provide: XSRFStrategy, useFactory: xsrfFactory }
  ],
  bootstrap: [ServerAppModule]
})
export class AppServerModule {}
This code creates a factory function 'xsrfFactory' that instantiates a CookieXSRFStrategy. This strategy configures how Angular should read the XSRF token from a cookie and set it as a header for outgoing requests. The 'AppServerModule' is then set up to use this strategy for XSRF protection by overriding the default XSRFStrategy with the one provided by the factory.
app.use(cookieParser());
app.use(csrf({ cookie: true }));

app.use(function (req, res, next) {
  var token = req.csrfToken();
  res.cookie('XSRF-TOKEN', token);
  next();
});
In your server (Express.js for example), use `cookieParser` to parse the cookies attached to the request. Use the `csrf` middleware to create a csrf token which is then set into a cookie with the name 'XSRF-TOKEN'. Angular will pick this token up and add it as a header to its outgoing requests.