/DunglasAngularCsrfBundle

Automatic CSRF protection for Symfony apps using AngularJS

Primary LanguagePHP

DunglasAngularCsrfBundle

This Symfony 2 bundle provides automatic Cross Site Request Forgery (CSRF or XSRF) protection for client-side AngularJS applications. It can also be used to secure apps using jQuery or raw JavaScript issuing XMLHttpRequest.

Build Status SensioLabsInsight

How it works

AngularJS' ng.$http service has a built-in CSRF protection system. To enable it, the server-side application (the Symfony app) must set a cookie containing a XSRF token on the first HTTP request. Subsequent XHR requests made by AngularJS will provide a special HTTP header containing the value of the cookie.

To prevent CSRF attacks, the server-side application must check that the header's value match the cookie's value.

This bundle provides a Symfony's Event Listener that set the cookie and another one that checks the HTTP header to block CSRF attacks. Thanks to DunglasAngularCsrfBundle, you get CSRF security without modifying your code base.

This bundle works fine with FOSRestBundle.

Installation

Use Composer to install this bundle:

composer require dunglas/angular-csrf-bundle

Add the bundle in your application kernel:

// app/AppKernel.php

public function registerBundles()
{
    return array(
        // ...
        new Dunglas\AngularCsrfBundle\DunglasAngularCsrfBundle(),
        // ...
    );
}

Configure URLs where the cookie must be set and that must be protected against CSRF attacks:

# app/config/security.yml

dunglas_angular_csrf:
  # Collection of patterns where to set the cookie
  cookie:
      set_on:
          - { path: ^/$ }
          - { route: ^app_, methods: [GET, HEAD] }
  # Collection of patterns to secure
  secure:
    - { path: ^/api, methods: [POST, PUT, PATCH, LINK] }
    - { route: ^api_v2_ }

Your Symfony/AngularJS app is now secured.

Examples

  • DunglasTodoMVCBundle: an implementation of the TodoMVC app using Symfony, Backbone.js and Chaplin.js

Full configuration

dunglas_angular_csrf:
  token:
      # The CSRF token id
      id: angular
  header:
      # The name of the HTTP header to check (default to the AngularJS default)
      name: X-XSRF-TOKEN
  cookie:
      # The name of the cookie to set (default to the AngularJS default)
      name: XSRF-TOKEN
      # Expiration time of the cookie
      expire: 0
      # Path of the cookie
      path: /
      # Domain of the cookie
      domain: ~
      # If true, set the cookie only on HTTPS connection
      secure: false
      # Patterns of URLs to set the cookie
      set_on:
          - { path: "^/url-pattern", route: "^route_name_pattern$", methods: [GET, POST] }
  # Patterns of URLs to check for a valid CSRF token
  secure:
      - { path: "^/url-pattern", route: "^route_name_pattern$", methods: [GET, POST] }

Credits

This bundle has been written by Kévin Dunglas.