Issues with performing Ajax requests within the Laravel and Vue.Js framework

After exhausting all my efforts trying to resolve this issue, I find myself stuck and frustrated. Despite including the CSRF token as suggested by various sources, the problem persists.

The route is utilizing the default 'web' middleware.

Confirmed Inclusion of CSRF Token

I have reached a point of desperation and any guidance or assistance on this matter would be greatly appreciated.

Working with the latest version of Laravel 5.7 with all components up to date

JS Script:

<script>
export default {
    name: "BankIdLogin",
    data() {
        return {
            status: '',
            error: '',
            message: '',
        }
    },

    created() {

    },

    methods: {
        initiateBankID: function (e) {
            e.preventDefault();
            e.stopPropagation();
            axios
                .post(
                    "/login/bankIdAuthentication", {
                        _token: $('meta[name="csrf-token"]').attr('content'),
                        ssn: $('#ssn').val()
                    }
                )
                .then(res => res.json())
                .then(res => console.log(res));
        },
        collectBankID() {

        }
    }
}
</script>

Response from the call:

{
   "message":"",
   "exception":"Symfony\\Component\\HttpKernel\\Exception\\HttpException",
   "file":"/var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php",
   "line":204,
   "trace":[...]
}

web.php

Route::post('/login/bankIdAuthentication', 'Api\LoginController@bankidAuthentication');

LoginController.php:

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\BankidSignature;
use App\Models\User;
use Frozzare\Personnummer\Personnummer;
use ILabs\Api\BankId;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends BaseController
{
public function bankidAuthentication(Request $request)
{
    $ssn = Personnummer::format($request->post('ssn'), TRUE) ?? $request->post('ssn');
    if ($ssn === '')
        $ssn = $request->post('ssn');

    if ($ssn !== '') {
        $user = User::where(
            [
                'ssn'    => $ssn,
                'active' => 1,
            ]
        );
        if (!$user->count()) {
            return \GuzzleHttp\json_encode(['status' => 0, 'message' => __('INVALID_SSN')]);
        }

        $bankid = new BankId();

        try {
            $bankid->bankIDAuthenticationRequest($ssn);

            session(['ssn' => $ssn]);

        } catch (\Exception $e) {
            return \GuzzleHttp\json_encode(['status' => 0, 'message' => $e->getMessage()]);
        }
    }
    return \GuzzleHttp\json_encode(['status' => 0, 'message' => 'Unknown Error']);
}
}

EDIT Issue resolved after disabling CSRF in the web middleware, revealing a potential CSRF-related root cause...

A discrepancy between the _token provided by the function and that stored in the session has been identified. Example:

_token from request: wiqBYqBdtMJL9JxInySSSBGtYzPGHAjePLNBILRz
_token in session: e5caPLy6N82QEQoUzixHAvojE2SortRKqxOFM3sI

Additional Request headers

EDIT 2 Further investigation indicates that Ajax calls create separate sessions, aligning with similar observations discussed here on Laracast - CSRF tokens

Despite attempting suggested solutions from the forum thread, no success has been achieved.

EDIT 3

Following a commit of changes, the issue miraculously resolves itself.

Answer №1

Ensure to include the following code snippet in your Html page that triggers the ajax request:

var bankIdAuthenticationRoute = "{{route('bankIdAuthenticationRoute')}}"
var csrf = "{{csrf_token()}}"

Utilize both variables in your Javascript file when making the Ajax call.

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

Having issues with Vue.js when using Vue-strap Radio Buttons

While developing my web application with vue.js, I encountered an issue with radio buttons when I switched to using bootstrap style. I understand that I need to use vue-strap for proper data binding with bootstrap styled radio buttons in vue.js, but I am s ...

Issue with THREE.CubeTextureLoader where edges appear 1px too small

My latest project involved creating a panorama cube using THREE.CubeTextureLoader: pano = [ 'scenes/4/2048/px.jpg', 'scenes/4/2048/nx.jpg', 'scenes/4/2048/py.jpg', 'scenes/4/2048/ny.jpg', 'scenes/4/ ...

Preventing the submission of a form using jQuery until all input, radio, select, and checkbox fields are filled out

I currently have a form that includes various field types, all of which must be filled out before submission. The submit button is disabled by default and I am looking to enable it once all fields are completed. I came across examples of this feature work ...

Choose particular columns from the related tables or models

In my N x 1 relationship, Post x User, the Post->User relation is defined as follows: Post.php (model): .... public function user() { return $this->belongsTo('User'); } .... My goal is to only fetch the id and username from the User ...

npm ERROR! 404 Content removed by unidentified source on August 8, 2022 at 09:20:35.527 UTC

Upon running the command <npm view e-biz-znnf versions --json> in the terminal, npm throws an error message: npm ERR! code E404 npm ERR! 404 Unpublished by undefined on 2022-08-08T09:20:35.527Z npm ERR! 404 npm ERR! 404 'e-biz-znnf' is no ...

Is adding ng-click in a template counterproductive to the concept of MV* architecture?

When working with AngularJS, you may come across instances where the ng-click handler is directly connected to an HTML element like <a> or <button>. Take for example the snippet below (borrowed from an Angular homepage sample), where the click ...

"Enhance your forms with Ajax for seamless uploading and convenient text

My current challenge involves submitting a form that features multiple file uploads using ajax along with text input. I'm facing an issue where if a user successfully uploads all the files using ajax but forgets to enter their name, the form resets an ...

Avoiding Incorrect User Verification through Sanctum in Laravel

I'm currently working on creating web services in Laravel that are secured by auth:sanctum. However, I would like to make an exception for a specific user who is logged in. The user with the following credentials: telephone: 0900 000 00 00 passw ...

Modify marker location as data updates

I am currently utilizing the Google Maps API within a Vue.js project. In my project, I have a table of data that includes positions, and I am looking to update the marker positions dynamically without refreshing the entire card. Below is the code snippet ...

What is the best way to organize Node/Express routes based on their type into different files?

My /router/index.js file is becoming too cluttered, and I want to organize my routes by group (user routes, post routes, gear routes) into separate files within /router/routes/. Here's what I currently have set up: app.js var express = require(&apos ...

When utilizing NavLink in React Router Dom for routing to an external link, a local host is automatically included in the prefix

I'm currently experiencing an issue with routing to an external link using React Router Dom 6.4. It seems that the localhost path is being appended to the URL. Can anyone provide insight on why this might be happening? localhost:3000/#/http://www.sav ...

What should be the output when ending the process using process.exit(1)?

I need to update my code by replacing throw new Error('Unknown command.') with a log statement and process.exit(1);. Here is the example code snippet: private getCommandByName = (name: string): ICommand => { try { // try to fetch ...

Check out this stylish Twitter-inspired SVG text counter created with a combination of CSS and jQuery! See it in action here: https://jsfiddle.net/moss24

Looking to develop a text counter similar to Twitter that increases the width in green color up to 75%, then switches to yellow until 98%, and finally turns red if the input value is greater than or equal to 400. It should also add a "highlight" class when ...

applying a blur effect to the Vue modal mask

Trying to incorporate a blur panel behind my modal using vue.js, however, The issue arises when the modal-mask contains nested content. This makes it challenging to apply the filter: blur() property without blurring everything. Currently, I am only able t ...

Combining Data in React Arrays

I have an array with different group types and I need to merge the results if the grouptype is the same. const locationss = [ { grouptype: "Name1", id: "1", servicetype: [ { name: "Morning", price: "5& ...

Delay the rendering of the MUI DataGrid column until after the DataGrid is visible on the screen

Would it be feasible to asynchronously load a column of data in the MUI DataGrid after the table is displayed on the screen? Retrieving this additional data from the database is time-consuming, so I aim to have it appear once the table has fully loaded. T ...

What is the process for deploying a next.js application with a custom express backend to a VPS or Heroku platform?

Does anyone have advice on deploying a next.js application with a custom express backend to either a VPS or Heroku? ...

What are the steps to creating a barcode scanner using JavaScript and a camera?

Hey there! I'm new to processing JavaScript and jQuery, so I could really use your expertise. My goal is to create a barcode reader using my phone's camera. So far, I've attempted the following: <video id="video" width="640" height=" ...

Does the ngIf directive cause a re-evaluation of variables when used with one-time-binding in AngularJS?

I recently had a colleague at work demonstrate a peculiar quirk with one-time binding in Angular. Scenario: Imagine having an element with text being bound using one-time binding inside a block that is conditional on ng-if. If you update the value, say b ...

Deleting Cart Items Permanently with AJAX in Vue.js and Shopify

Seeking assistance with implementing a feature to remove a product from a MiniCart using Vue.js in a Shopify theme. Below is the code snippet for minicart.liquid file along with the cart data stored in the 'data' property. Although the remove fun ...