Search code examples
angularjselixirphoenix-frameworkcsrf-protectionplug

CSRF Protection in Phoenix and Angular


I have an Angular App for which i intend to use Phoenix as backend. Phoenix supports CSRF protection by default where the CSRF token is stored to session. This works fine when Phoenix is rendering views, but how do i get access to CSRF token when my front end is built using Angular js. Currently, i am making a get request to get_csrf_token() menthod but i am looking for better solution.

csrf_token = get_csrf_token()

NOTE: You can suggest any other elixir framework that supports CSRF Protection too.


Solution

  • You can store the CSRF Token in a meta tag with csrf_meta_tag/0 in you app layout, then read it from angular and set it as default header for $httpProvider:

    angular.module('MyApplication', []).config(["$httpProvider", function ($httpProvider) {
      var token = document.querySelector('meta[name=csrf-token]').content;
      $httpProvider.defaults.headers.common['X-CSRF-Token'] = token;
    }])