0

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.

Himanshu Gupta
  • 305
  • 3
  • 12

1 Answers1

3

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;
}])
Patrick Oscity
  • 53,604
  • 17
  • 144
  • 168
  • SInce I am serving views through Angular, I don't have layout in phoenix. Where should i call csrf_meta_tag then? Note: I install project using --no-html tag in mix phoenix.new – Himanshu Gupta Jun 01 '17 at 10:29
  • Well it's up to you then to figure out a way to communicate with the server to receive the csrf token, for example with a separate REST endpoint to obtain a csrf_token. Also see this question for someone that had a very similar problem: https://stackoverflow.com/questions/33179747/springs-csrf-protection-for-a-html-only-login-page – Patrick Oscity Jun 01 '17 at 11:25