Exploring AngularJS and CSRF security measures when using RESTful APIs in Laravel

Struggling to figure out how to get this functioning properly... I'm attempting to retrieve the CSRF from the API and use it as a constant in my AngularJS application. The code snippet I used is from @David Mosher, found here: https://gist.github.com/davemo/6141699. I kick off the app.js by doing this:

    // Obtain and inject the CSRF token from the server
(function() {
  var $injector = angular.injector(['ng']); $injector.invoke(function($http,$rootScope) {
    $rootScope.$apply(function() {
      $http.get("http://api.local/auth/csrf_token").then(function(response)
      {
        angular.module("app").constant("CSRF_TOKEN", response.data);
        console.log(CSRF_TOKEN);
        angular.bootstrap(document, ['app']);
      });
    });
  });
})();

Upon checking, I receive a 200 status code along with the csrf_token. However, the CSRF_TOKEN seems to not be set within the app... the console.log(CSRF_TOKEN) results in a ReferenceError: CSRF_TOKEN is not defined....

Any insights into what I might be missing or doing incorrectly??

Thank you for your help! :-)

Answer №1

I incorporate angular into my laravel project as well. Here is the approach I take, and it has proven to be effective:

To initiate angular, I use the following code snippet (I include double brackets for compatibility with blade {{ syntax):

var laravelApp = angular.module('laravelApp', ['ui.bootstrap', 'ngResource'], function($interpolateProvider) {
    $interpolateProvider.startSymbol('[[');
    $interpolateProvider.endSymbol(']]');
});

In my index.blade.php file, I set the CSRF token as a constant:

@section('javascripts')
    <script>
        angular.module("laravelApp").constant("CSRF_TOKEN", '{{ csrf_token() }}');
    </script>
@endsection

Additionally, in my Controller, I make use of this CSRF_TOKEN constant within my angular application:

laravelApp.controller('startCtrl', function($scope, $http, CSRF_TOKEN, $window) {

    // initialization
    $scope.init = function () {
        $scope.template_choose = 'start';
        $scope.loadTemplateURL = '/template/load';
    }

    // Sending POST Request with csrf_token
    $scope.loadActualTemplate = function() {
        $http.post($scope.loadTemplateURL, {
            '_token' : CSRF_TOKEN
        }).then(function(Response) {
            $scope.template_choose = '/template/choose/'+Response.data;
        });
    }

    // starting point
    $scope.init();
});

Remember to define your CSRF_TOKEN in your blade template, pass it to your controller, and utilize it as a Post Parameter in your $http.post method. This methodology has been successful for me.

Answer №2

Place the provided code at the beginning of your services.js file, if it exists

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to implement loading an external script upon a page component being loaded in NextJS

I recently transferred an outdated website to Nextjs and I am having trouble getting the scripts to load consistently every time a page component is loaded. When navigating between pages using next/link component, the scripts only run the first time the ...

When using Observables in AngularFire2, the $ref property does not get captured

Recently, I started working with AngularFire2 (version 4.0.0-rc.1) and encountered a challenge that has me stuck: getWishlist$(): FirebaseListObservable<{}> { return <FirebaseListObservable<{}>>this.store.select(getFirebaseUID) ...

What could be causing the issue of CSS animation not functioning properly when used in conjunction with a

I am working on creating a switch button with CSS and JavaScript that needs an animation when toggling or clicked. The only issue I am facing is related to the animation. I am wondering if there might be any problem with the positioning (relative, absol ...

Executing Knex promises sequentially within a for loop

I have recently started to dive into Node and asynchronous coding, but I am struggling with a fundamental concept. I am trying to seed a database using knex, reading data from a CSV file and iterating through the rows in a for loop. In each iteration, I ne ...

Calculating the mean value of an array containing objects with a single key-value pair in JavaScript

I have a list of users along with their ages, and I need to calculate the average age of all users. I initially attempted to use the reduce method for this task, but encountered syntax errors preventing successful implementation. Below is the code snippet ...

Can you explain the concept of F-Bounded Polymorphism in TypeScript?

Version 1.8 of TypeScript caught my attention because it now supports F-Bounded Polymorphism. Can you help me understand what this feature is in simple terms and how it can be beneficial? I assume that its early inclusion signifies its significance. ...

Acquiring asynchronous data using AngularJS

Currently in the process of designing a company page that dynamically loads specific elements based on the logged-in user. For instance, when a company accesses their account details in the dashboard, only their relevant information such as name and descri ...

The `Click()` functionality experiences malfunction in Protractor automation scripts

I am currently automating my tests using Protractor and Appium for an AngularJS website with the Jasmine framework in an iPad simulator. Although the sendkeys() function is working fine for entering the username and password, I am facing issues when clicki ...

Unraveling Objects: Simplifying object structures in JavaScript using AngularJS

I received an object from the backend and I need to extract its elements to attach them to the scope for viewing. The structure of the object is as follows: { "Name": { "S": "Jon Snow" }, "Location&quo ...

Having trouble locating images and JavaScript files on GitHub Pages

Using a template from this source to create a react website with interactions involving smart contracts, I successfully got everything up and running smoothly on my localhost. All the features of the site were functioning correctly and images were displayi ...

React not displaying wrapped div

I am facing an issue with my render() function where the outer div is not rendering, but the inner ReactComponent is displaying. Here is a snippet of my code: return( <div style={{background: "black"}}> <[ReactComponent]> ...

Positioning a material UI dialog in the middle of the screen, taking into account variations in its height

Dealing with an MUI Dialog that has a dynamic height can be frustrating, especially when it starts to "jump around" the screen as it adjusts to fit the content filtered by the user. Take a look at this issue: https://i.stack.imgur.com/IndlU.gif An easy f ...

My socket io connection is not working. There seems to be an issue with the connection io

After initiating my server, I am able to see the console.log message showing that the server is running on the specified port. However, I am not receiving the console.log message indicating a successful socket io connection with a unique socket id. import ...

Is it possible to obtain the index of a table row using querySelector?

Is it possible to find the rowIndex of the first occurrence of a table row within the #myTable using JavaScript? http://jsfiddle.net/bobbyrne01/fmj6np6m/1/ html .. <table id="otherTable"></table> <table id="myTable"></table> js ...

When echoing SESSION in PHP, the previous value is displayed

<script language="javascript"> function handleEmergency() { if(document.getElementById('emer').checked == true) { <?php $_SESSION['total2']= $_SESSION['total1'] ...

In Laravel, what does $query->time unit represent?

As per the Laravel documentation, it is stated that it is viable to incorporate a listener that will record all SQL queries along with their durations. public function boot() { DB::listen(function ($query) { // $query->sql // $qu ...

Navigating through HTTP promises in AngularJS can be tricky, but with the

Having trouble fetching data from an http promise response and setting it as an attribute in a custom directive. I keep receiving undefined data in my directive every time. promiseComboBox.then((response) => { $scope.comboBoxTipoParking = r ...

Access to JSON.stringify is prohibited

I have an array containing objects in JavaScript that I need to save as a .json file. Prior to saving the objects, I displayed them using console.log. // Client Object {id: "1", color: "#00FF00"} Object {id: "2", color: "#FF7645"} Object {id: "3", color: ...

The masonry reorganization is behaving strangely

I've recently started using masonry for the first time and you can check it out here: Although I have managed to set it up, I am facing some issues with its positioning of boxes when dragging items in. For example, instead of placing a medium-sized ...

Tips on creating an inline editable cell in a Tree View

I've been working on a category tree that includes expand and collapse buttons. You can see what I have so far here: Category Tree Now, I'm looking to make each item inline editable. Can someone guide me on how to achieve this? If you want to t ...