The JWT authentication token is not valid for routes outside of the /api endpoint

Encountering an issue with JWT authentication token while using Laravel's broadcasting feature. The error message received is: {error: "token_invalid"}

Puzzlingly, the token appears to be valid as it works perfectly fine on /api routes but fails on non-api routes like /broadcasting/auth. Additionally, validating the token on jwt.io shows that it is indeed correct.

Any insights or solutions for this problem?

#----------------------------------
# api.php
#----------------------------------

Route::group(['middleware' => 'jwt.auth'], function () {
    Route::apiResource('flights', 'Api\\FlightControllerAPI');
    Route::apiResource('airlines', 'Api\\AirlineControllerAPI');
});
#--------------------------------
# BroadcastServiceProvider.php
#--------------------------------

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Broadcast;

class BroadcastServiceProvider extends ServiceProvider
{
    public function boot()
    {
        // Broadcast::routes();
        Broadcast::routes(['middleware' => ['jwt.auth']]);

        require base_path('routes/channels.php');
    }
}
#----------------------------
# app.js
#----------------------------

/**
 * Loading all JavaScript dependencies including Vue and other libraries.
 */

require('./bootstrap')

window.Vue = require('vue')

import Echo from "laravel-echo";

window.Pusher = require('pusher-js');

var token = "<Your JWT Token Here>"
window.Echo = new Echo({
    broadcaster: 'pusher',
    key: '<Your Pusher Key>',
    cluster: 'ap1',
    encrypted: true,
    auth: {
        headers: {
            Authorization: "Bearer " + token
        }
    }
});

export const serverBus = new Vue()

import axios from 'axios';
import VueAxios from 'vue-axios';
import App from './views/App.vue'
import router from './routes'

axios.defaults.baseURL = '/api'

Vue.use(VueAxios, axios)

Vue.router = router

Vue.use(require('@websanova/vue-auth'), {
    auth: require('@websanova/vue-auth/drivers/auth/bearer.js'),
    http: require('@websanova/vue-auth/drivers/http/axios.1.x.js'),
    router: require('@websanova/vue-auth/drivers/router/vue-router.2.x.js'),
})

const app = new Vue({
    el: '#app',
    router,
    render: app => app(App),
})

Answer №1

Just encountered a problem and found a solution. I decided to try accessing /test?token=current_token after creating the test route in web.php, but I received an exception stating "this token has been blacklisted."

To resolve this issue, I simply disabled it by adding the following line: JWT_BLACKLIST_ENABLED=false to the .env file, and everything started working as expected.

#--------------------
# web.php
#--------------------

Route::get('/test', function () {
    return JWTAuth::parseToken()->authenticate();
});

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

Troubleshooting a Vue 2 component's prop receiving an incorrect value

I'm currently working on creating a menu that navigates between categories. When a category has a sub-category, it should return a boolean value indicating whether it has a sub-category or not. <template> <select><slot></slot ...

Discord.js: AbortError: The request was cancelled by the user

Recently, while working on my ticket system and the process for logging transcripts, I encountered an unexpected error that caused transcripts to fail sending. This issue never occurred before. The error message displayed was: [Error Handling System] Multi ...

Tips for including a verification symbol next to your username

How can I implement a verification badge next to a user's username on a website using jQuery, JavaScript, PHP, HTML, and CSS? Currently, I am using isset($user[verification]) to display the badge, but I believe this approach is not optimal as it requi ...

The data provided is not in the correct format for a timestamp

Currently, I am utilizing the pg node module to establish a connection with PostgreSQL, and I have been attempting to run the following query: const res = await client.query(`SELECT number_transactions FROM transaction.city_unique_dates WHERE date_day_t ...

The lack of definition for the Nuxtjs document is causing an issue

Currently, I am in the process of setting up a reviews page within nuxtjs. To achieve this, I have integrated the vue-star-rating library into my project. However, I have encountered an error despite attempting various solutions that have worked for others ...

tips for adding text to an input field after it has been submitted

Is there a way to automatically add text to an input field after the user has entered their information? For example, if a user types "youtube.com" into a search bar, could the input then apply ""? ...

No element found with the specified exportAs value of "ngForm" on the <form> tag

I am currently experimenting with a template driven form in Angular, but I encountered an error stating **There is no directive with “exportAs” set to “ngForm"** I have made sure to import FormsModule and ReactiveFormsModule in app.module.ts as well ...

Secure your data with public key encryption and decryption using the Crypto Module in NodeJS

I have a challenge with encrypting/decrypting data using a public key that is stored in a file. The code snippet below illustrates my approach: encryptWithKey (toEncrypt, publicKeyPath) { var publicKey = fs.readFileSync(publicKeyPath, "utf8"); ...

Sending a post request with data to an ExpressJS server resulted in a 404 error indicating that the server

My setup includes a React frontend communicating with my own ExpressJS API backend running version 4.16.0. Currently, using the fetch method in the React frontend to retrieve data is functioning properly: fetch('/desResData') .then(res = ...

Customizing Material UI tooltip styles with inline CSS formatting

Currently in the process of creating a React component that utilizes the Material UI Tooltip feature. In my component, I have the need to manually reposition the Mui Tooltip by targeting the root popper element (MuiTooltip-popper). However, the Mui Toolti ...

Guide to continuously polling a GET request in JavaScript until the response status is successful

In my JavaScript code, I have a function that utilizes AJAX to send a GET request. The response from the request can be either success, fail, or in process if the job is still running. I want this function to continuously send the GET request every few s ...

Creating diverse options using attribute-value pairs

I am in need of creating an array that contains all possible combinations of attribute values. Here is an example of my attributes/values object: let attr = { color: ['red', 'green', 'blue'], sizes: ['sm&apo ...

Tips for making multiple files accessible in an npm package?

I have developed an npm package called example-package. Typically, users would import it like this: import RootModule from "example-package"; However, I also have a file nested within the package structure. Package Root > src > Feature > inde ...

Displaying an image prior to the component rendering in Vue.js

In my Vue application, I have a list of events that are displayed individually. When I visit the page of a selected event, an error message appears in my console: GET http://localhost:1337/undefined 404 (Not Found). However, the image still loads correctly ...

Printing feature not functioning properly on Internet Explorer version 11

Currently, I am facing an issue with printing a document using a blob URL and iFrame. Everything works perfectly in Chrome, but unfortunately, it's not functioning properly in IE browser. I need guidance on how to successfully print a blob URL that i ...

Harnessing the Power of Global Configuration in React

Lately, I've been delving into the world of ReactJS. One thing I'm trying to figure out is how to establish a global configuration variable like SERVER_IP_ADDR. My goal is to be able to use this global configuration variable when making API req ...

How to install Typed.js without using Node.js

I'm currently working on a project that requires the JavaScript library typed.js, however, I am using the free webhost 000webhost which does not support Node.js. Since typed.js is typically installed using Yarn, NPM, or Bower - all of which require No ...

The issue with ng-change is causing the previously selected drop down option to be cleared

After successfully implementing live searching with ng-change, I encountered an issue with a pre-selected drop-down box. Despite setting the selected="selected" attribute to make option three the default selection, the drop-down box jumps to the top optio ...

When passing a numeric value like 1 or 2 to the function in ajax, it functions correctly. However, when attempting to parse a variable, it does

I am facing an issue with my AJAX function. It works perfectly fine when I pass a number as a parameter, but not when I pass a variable. function display_message(userID) { $.ajax({ url: "displaychat.php", method: "post", data: { toui ...

Duplicate a DOM element and incorporate animation into it

After extensively researching articles and documentation on this topic, I have yet to find a solution that aligns with the approach I am attempting to implement. My scenario involves an array of category items which contain a nested array of products be ...