AngularJS CSRF token constant

Submitted by xtrasmal - 10 years ago

Do not trust the client. Safe way to get CSRF token for use in Angular JS. Keeps it as a constant.

///////////////////////////////////////////////////////////////////
// PHP
// Just create your routes for Auth, and this one to return a token
///////////////////////////////////////////////////////////////////
// route:
Route::get('/auth/token', 'App\Modules\Auth\Controllers\AuthController@token');
// controller action
class AuthController extends \BaseController{

    public function token()
	{
		return csrf_token();
	}

}



//////////////////////////////////////////////////////
// JS, I'm using AMD and Require.js
// --------------------------------
///////////////////////////////////////////////////////
require.config({
    paths: {
		'angular'			: 	'libs/angular/angular.min',
		'app'				: 	'app/app',
		'filters'			: 	'app/filters/filters',
		'services'			: 	'app/services/services',
		'directives'		: 	'app/directives/directives',
		'controllers'		: 	'app/controllers/controllers',
	},

	shim: {
		'angular' 			: 	{'exports' : 'angular'},
		'app'				: 	{deps:['angular']},
		'ngSanitize'		: 	{deps:['angular']}

	},

	priority: [
		'angular'
	]
});

require( ['angular','app'], function(angular, app) {

	'use strict';

	angular.bootstrap(document, ['App']);

});
/////////
// APP JS
/////////
define([
    'angular',
	'filters',
	'services',
	'directives',
	'controllers'
	], function (angular, filters, services, directives, controllers)
	{

		'use strict';

		// Get token from route

    	var xhReq = new XMLHttpRequest();
			xhReq.open("GET", "http://"+window.location.hostname+"/token", false);
			xhReq.send(null);

		var app = angular.module('App', ['App.filters', 'App.services', 'App.directives','App.controllers'])

			// Token to contant

			.constant("CSRF_TOKEN", xhReq.responseText)

			// Laravel blade uses {{}}, so let's change it to (())

			.config(function($interpolateProvider)
			{
				$interpolateProvider.startSymbol('((');
				$interpolateProvider.endSymbol('))');
			});

	}
);

/////////
// CONTROLLERS JS
/////////
define(['angular', 'services'], function (angular) {

    'use strict';

	return angular.module('App.controllers', ['App.services'])
	
    .controller("LoginController", function($scope,$state, $location, AuthenticationService) 
		{
			$scope.credentials = { email: "", password: "" };
			$scope.login = function() 
			{
		    	AuthenticationService.login($scope.credentials).success(function() 
		    	{
		      		$location.path('/');
				});
			};
		});
});     

/////////
// SERVICES.JS
/////////
define(['angular','app'], function (angular) {

    'use strict';

	return angular.module('App.services', ['App.filters'])

		.factory("AuthenticationService", function($http, $sanitize, CSRF_TOKEN)
		{

			var sanitizeCredentials = function(credentials)
			{
				return {
					email:  	$sanitize(credentials.email),
					password: 	$sanitize(credentials.password),
					csrf_token: CSRF_TOKEN
				};
			};

			return {
				login: function(credentials)
				{
					var login = $http.post("/auth/login", sanitizeCredentials(credentials));
					login.success(cacheSession);
					login.error(loginError);
					return login;
				}
			};
		});
});