Inject Laravel 4 CSRF Token into AngularJS

Get Your Free AngularJS 2 Book Chapters

Also get the AngularJS exclusive deals and freebies direct to your inbox for FREE!

At some point you might want to add some basic security to your AngularJS web application. Assuming your reading this because your using Laravel 4 for your back-end. So, you can use the built in CSRF protection which Laravel provides out of the box! When your web application starts you can bootstrap your main AngularJS module with a CSRF token as a constant and send it with every AJAX/HTTP request you make to your back-end to authenticate the client.

I have seen a whole heap of different methods to do this, and it all depends on your preference and what web technologies your using. For example, you could like using cookies or could be using AMD/Require.js with Angular. You may not even be using Laravel, you could be using something different PHP or even node.js. I also cover below different ways to create and Handling CSRF Tokens in Laravel 4.

Example 1 – Inject using a META tag and ng-init

One way to inject server side values into AngularJS is to use ng-init (binds to the scope in which it is declared, in our case it’s the root scope) So when we load our application it will put the csrf_token on our root scope (ng-app=”app”). Doing it this way we can avoid making an extra HTTP request for the token when our application loads.

We can then access it using the following (usually into our ng authentication service where we can ask for it with our login credentials):
$scope.csrf_token;

Alternatively.

Instead of using ng-init you read the value directly into your app. For example, store the token in a meta tag then adds it to the headers of every request. You can do this by setting the $http provider to include the token in the request header:

Then you can inject the CSRF_TOKEN as a constant in your authentication service just as shown in example 2. Credit to David Mosher’s Gist for this one thanks mate.

Creating and Handling CSRF Tokens in Laravel 4

So the front-end is done, here is a bunch of different ways to create and handle CSRF tokens in Laravel 4. They use Laravel 4 filters and apply those filters to specific routes to secure your application.

Notes:

You will also need to set an Encryption key in your app/config/app.php file. This key is used to create unique csrf tokens with a session (it essentially uses the key as hash). You can generate this key by running this command:
php artisan key:generate.

Related Posts

Angularjs4u.com is not endorsed or certified by AngularJS. All AngularJS logos and trademarks displayed on this blog are property of AngularJS.
The views expressed on here are purely to help other developers use AngularJS.