When I try to access protected routes in Laravel using only HTTP cookies, I keep receiving a 401 Unauthorized error message while making requests with

While developing a Laravel application with JWT authentication, I encountered an issue when trying to utilize http-only cookies for authentication. Despite properly setting the cookie upon login, I continued to face a 401 Unauthorized error when attempting to access protected routes using axios. Below is my current setup:

$token = JWTAuth::claims($claims)->fromUser($user);
$cookie = Cookie::make('auth_token', $token, 60, null, null, false, true, false, 'Strict');

if ($user->status == 'active' && $user->is_verified == 1) {
    return response()->json([
        'message' => 'User logged in successfully',
        'token' => $token,
        'user' => UserService::data($user->id)
    ], 200)->withCookie($cookie)
      ->header('Access-Control-Allow-Credentials', 'true')
      ->header('Access-Control-Allow-Origin', 'http://localhost:5173')
      ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
      ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
}

Axios Configuration

public async apiRequest(endpoints: { [key: string]: Record<any, any> }, method: string = 'POST'): Promise<{ [key: string]: any }> {
        axios.defaults.withCredentials = true;
        const axiosInstance: AxiosInstance = axios.create({
            baseURL: this.url,
            withCredentials: true,
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
            },
            timeout: 40000,
        });

        const payload: { [key: string]: string } = {};

        for (const [endpoint, data] of Object.entries(endpoints)) {
            const pre= `__${endpoint}`;
            payload[pre] = encryptData(data);
        }

        try {
            const response: AxiosResponse<ApiResponse> = await axiosInstance.request({
                url: '/request.json',
                method: method,
                data: JSON.stringify(payload)
            });

            return response;

        } catch (error: any) {
            if (axios.isAxiosError(error) && error.response?.status === 401) {
                this.logout();
            }
            console.error('Error making request:', error);
            throw error;
        }
    }

My Middleware

Route::group(['middleware' => 'api'], function ($router) {
    Route::match(['GET', 'POST', 'PUT', 'PATCH', 'DELETE'], 'action.json', [RequestController::class, 'handle']);
    Route::post('/request.json', [ApiController::class, 'handle']);
});

public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login', 'signup', 'password/reset', 'reset', 'test', 'getUser']]);
    }

Despite these configurations, I am still encountering a persistent 401 Unauthorized error when accessing protected routes.

How can I troubleshoot and eliminate the 401 Unauthorized error while ensuring that my http-only cookies are validated correctly for authentication in Laravel?

Here are my attempted solutions:

  • Confirmed supports_credentials is set to true and allowed the correct origin.
  • Implemented withCredentials: true in the axios requests.
  • Verified that the routes are safeguarded with the appropriate middleware.

I aim to execute API calls to the server without storing the token on the client side.

Answer №1

Have you attempted to make a request using Postman and confirmed that Laravel is functioning correctly?

If so, the issue may lie on the JavaScript side.

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

Loading an array in batches using javascript

Possible Duplicate: Wait until all jquery ajax request are done? I am faced with the task of loading elements from an array via AJAX using jQuery. I have successfully implemented the logic for loading each element, but now I need to load them in batch ...

Something's not quite right with my JavaScript content gallery

Query: What could be causing the issue of my script displaying blank content on the 7th interval (ID:img_7)? All the IDs from img_1 to img_6 are updating properly, but once it reaches the seventh interval, it's empty. In my script, I initialize a va ...

Verification of radio selections

I have successfully implemented validation for the radio button. Now, I would like to add an alert box that asks "Are you sure you want to pick 'x'?" before proceeding with the code. If the user clicks cancel, they should return to the webpage. B ...

Upon submission, the form is processed and 'false' is returned

Does anyone know how I can use ajax to save form data? I am encountering an issue where the page refreshes when all entries are correct. If I input any incorrect data and submit, it displays an error. However, if I then fill in all correct information, it ...

Obtain the full HTML code for a Facebook album

I am attempting to extract the HTML code from a Facebook album in order to retrieve the photo links. However, since not all photos load at once, cURL only retrieves the links of photos that are initially loaded. Is there a way to fetch the entire loaded H ...

Capturing Screenshots with Ionic Framework

I am currently working on an Ionic application that utilizes geolocation via the Google API. However, I am facing a challenge with implementing a feature where a button in the upper right corner should take a screenshot and trigger a popover with options t ...

When I start scrolling down, the Jumptron background image vanishes

Utilizing bootstrap jumptron with a background image has led to an issue where the background image disappears as I scroll down, leaving only the jumptron div class displaying the heading. How can this be fixed so that the image remains visible even when s ...

Sort div elements based on checkbox filters

I have a set of checkboxes that I want to use for filtering purposes. <div class="filter"> <div class="checkbox"> <label><input type="checkbox" rel="canada"/>Canada</label> </div> <div class="chec ...

Having trouble compiling Sass with "npm run watch" in Laravel?

Currently, I am enrolled in a Laravel course on Udemy where all the styling is done in Sass. Despite following the exact steps as the instructor, I encountered errors while he did not. Could someone please assist me with this issue? It's worth noting ...

Guide to selecting a checkbox in Vue.js 2 based on a specific value?

I'm currently working on setting up a roles and permissions system for my application. For the frontend, I am using Vue.js2 and for the backend, Laravel 5.4. Below is the allRoles array containing all roles fetched from the database: data: { // ...

The submission of the HTML form is not functioning as expected

Currently, I am delving into the world of coding and experimenting with HTML and PHP. I encountered an issue with a contact form created in HTML - when clicking the submit button, nothing appears on the screen. My immediate goal is to retrieve the entered ...

Can you guide me on how to initiate a fund request through the Coinbase API?

Hello, I am currently working on integrating the Coinbase API in PHP. The implementation is going smoothly as I can check balances, create new addresses, and more without any issues. However, I'm encountering a problem when trying to request bitcoin. ...

Struggling with displaying nested JSON data in React components

I have a nested JSON structure running on my local server, and I'm using React to practice displaying this nested data. Currently, I am focusing on showing the day and the available time slots for that day. I have managed to extract the "days" (mon, t ...

"Bootstrap's modal-backdrop element presents a striking fade effect as it

Issue I am facing a problem related to Bootstrap, specifically with a modal in my HTML file. Whenever I call the modal, it appears with a fade-in effect. The code for my modal: <div class="modal fade" id="exampleModal" tabindex=& ...

``motioning a component beneath another component that may be in a state

Having an issue with my CSS. I have some elements generated by JavaScript and when hovering over them, another element is displayed below the others for some reason. Here's the CSS related to this problem: .hiddenTextjob { display:none; ...

Using the id from a foreach loop to trigger a jQuery modal

I would like to trigger the modal opening when the user clicks on the create asset button. After filling in the modal fields and clicking the save button, I also need to retrieve the asset group ID along with the modal data using a foreach loop and send it ...

Issue of memory leakage while working with promises

My node.js cluster is set up with a primary that manages worker cycles (in the while loop) and listens to worker messages for progression in the cycle. (In this code snippet, I simplified the structure to highlight the issue) Server.js var cluster = requi ...

Encountering the following error: Exceeded maximum call stack size limit

Currently, I am attempting to tackle a specific problem on LeetCode. This particular challenge involves calculating the power of x. However, upon executing my solution, an error message is displayed: RangeError: Maximum call stack size exceeded Here&apos ...

Error: A variable is potentially 'undefined' (ts2532), even though I have just assigned a value to it

Encountering Object is possibly 'undefined'. ts(2532) errors in TypeScript for an optional parameter, despite being clearly defined... interface Foo { keyValue?: Record<string, string> } const a: Foo = { keyValue: { key1: 'value&apo ...

Which mobile tab switches should be tuned in to?

Within my React code, I have implemented a function to track the reconnectedCallback when using the following snippet: import { useEffect, useState } from "react"; import usePrevious from "../usePrevious"; const useTabVisible = (reco ...