Combining session and token guard in Laravel 5.2 for simultaneous route access

We previously used session guard for authorization and found it sufficient.

Now, we are in need of adding authorization through tokens (either in headers or GET parameters) while still using session authorization on the same routes.

The token-based authorization must be stateless.

UPDATE: Initially, we considered creating duplicate routes - one for session authorization and another for token authorization.

// API token authentication
// URL: /api/test
Route::group(['middleware' => ['web', 'auth:api'], 'prefix' => 'api', 'as' => 'api.'], function () {
    Route::resource('test', 'TestController');
    // 50+ routes
});

// Session authentication
// URL: /test
Route::group(['middleware' => ['web', 'auth']], function () {
    Route::resource('test', 'TestController');
    // 50+ routes
});

However, this approach did not meet our requirements as the URLs were different.

Is there anyone with a solution to address this issue?

Answer №1

Introducing a new middleware named AuthenticateWithToken:

class AuthenticateWithToken
{
    /**
     * Manage an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     *
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if (($user = Auth::guard('api')->user())) {
            Auth::setUser($user);
        }

        return $next($request);
    }
}

Add the declaration in Http/Kernel.php:

/**
 * The application's route middleware.
 *
 * These middlewares can be grouped or used individually.
 *
 * @var array
 */
protected $routeMiddleware = [
    // ...
    'auth.api' => \App\Http\Middleware\AuthenticateWithToken::class,
    // ...
];

Also include it before the default 'auth' middleware in routes.php:

Route::group(['middleware' => ['web', 'auth.api', 'auth']], function () {
    Route::resource('test', 'TestController');
    // More than 50 routes
});

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

The Vuejs component I created is failing to display on my Blade View

I can't seem to render my Vuejs component in my blade view. Any idea what I might be doing wrong? The specific component causing issues is named "star-rating". Blade View <div class="container"> <div class="row"> <div class="col- ...

What is the best way to create a MySQL query using the JSON data provided?

Here is the example data that is being sent to the PHP script: [{"id":1,"due_date":"2011-09-03","due_amount":"48279.00","wo_interest":"45980.00"}, {"id":2,"due_date":"2011-10-03","due_amount":"48279.00","wo_interest":"45980.00"}] The table fields are in ...

Utilizing the SELECT last_insert_id method for generating distinct and sequential identifiers

After exploring various options on different platforms, I have yet to find a solution that fits my specific scenario... SITUATION: I am working with a php system that automatically creates mysql-connected templates. For the system to function properly, e ...

Utilizing AJAX and jQuery to dynamically load a div instantly, followed by automatic refreshing at set intervals

I am utilizing jQuery and AJAX to refresh a few divs every X seconds. I am interested in finding out how to load these divs immediately upon the page loading for the first time, and then waiting (for example, 30 seconds) before each subsequent refresh. I h ...

Querying a MySQL database using PDO

After exploring various resources like How to create a secure mysql prepared statement in php?, I am still facing issues. When attempting to select data using parameters for column and table, the returned array is empty. Any suggestions or advice would be ...

In PHP, we divide a number by 10 and then increase the result by 1 if it is greater than

I am new to coding and I am grappling with how to correctly assign a value to a variable. The calculation for this variable involves dividing by 10, and if the result is not a whole number, I must add 1 to it. For instance, if I divide 294 by 10, I end up ...

The Laravel background-image:url function is yielding a result of 1

Currently working on a web application built in Laravel and encountered an issue with the code snippet below: <div class="user-info" style="background-image:url({{ asset(Auth::user()->partner->background) or '/images/default/background1.jpg& ...

Building Pagination Feature in Node.JS and Express using SWAPI and Axios

After numerous attempts, I managed to retrieve data from SWAPI but only the first 10 people were being displayed. Seeking a solution, I found that utilizing async functions was the key. const express = require("express"); const router = express.R ...

When searching for Arabic letters in PHP MySQL, the results may not always be displayed due to their different shapes

Having an issue with searching for Arabic letters as they have different shapes, like أ إ ا ي ى ه ة Each of these letters have a different unicode value. When entering a letter such as (ا), the search query should retrieve all words containing a ...

The PHP content form is malfunctioning and not processing email submissions properly, resulting in the PHP code being

Following a tutorial, I attempted to create a basic contact form using PHP. As a beginner in PHP, I found the process fairly straightforward, but encountered some bugs in the code. Upon integrating the code on my website, clicking the submit button redirec ...

Easy PHP navigation options

Creating a basic PHP page with includes is proving challenging when it comes to navigating URLs using '../' to find the correct path to the folder. Is there a straightforward way to set up a simple PHP navigation without involving MySQL or other ...

Is there a way I can obtain the code for a message box?

When I refer to a message box, I am talking about a container that gives users the ability to input their text and access different features like BOLD, ITALIC, color, justify, etc., in order to customize their message's appearance! (Think of it as the ...

Leveraging the routing functionality provided by Laravel exclusively

I'm curious to find out if it's feasible to leverage the exceptional routing feature that Laravel offers without incorporating other elements of the framework. It's a modest project and I prefer not to integrate the entirety of Laravel. ...

Selecting Content Dynamically with jQuery

I have a webpage with multiple dynamic content sections. <div id="content-1"> <div id="subcontent-1"></div> <i id="delete-1"></i> </div> . . . <div id="content-10"> <div id="subcontent-10"></d ...

Issue with Jquery firing function during onunload event

I'm having trouble adding a listener to a form in order to trigger an ajax call when the user leaves it. I can't seem to identify any errors in Firefox and nothing is getting logged in the console, indicating that my code might be incorrect. As s ...

The semantic UI search functionality is malfunctioning

My experience with semantic ui involves encountering an issue where the search result on a website appears empty, despite finding the JSON result in my console. This is the JavaScript code I am using: $('.ui.search').search({ apiSettings: { ...

Tips for creating a PHP cURL request using the provided documentation

Can anyone help with creating a PHP cURL based on the following documentation? Here is the raw curl text: curl --location --request POST '/serviceRates' \ --header 'Content-Type: application/json' \ --header 'acce ...

Running Javascript based on the output of PHP code

I have been working on my code with test.php that should trigger some Javascript when my PHP code, conditional.php, detects input and submits it. However, instead of executing the expected "Do Something in Javascript," it outputs "Not empty" instead. I fin ...

Increment the text counter following the uploading of an image file with html format

I have a form in which I am checking the character limit that a user can input into a text field using the 'onkeyup' attribute to update it in real time. Now, I want to achieve a similar function for image uploading. When a user selects an image ...

I am looking to eliminate the double quotation marks from a JSON file so that I can properly utilize

How can I successfully save a JSON return into an NSDictionary when there are spaces and double quotes present in the data? Is it possible to parse SBJSON to remove the double quotes before saving to rowsArray? rowsArray: { Rows = ( { ...