0

I'm working on a Laravel project where I'm using JWT (JSON Web Token) for user authentication. The authentication process seems to work correctly, as the JWT token is available in the browser's Dev Tools as a cookie when the user logs in.

However, I've implemented middleware to protect certain routes and check for the presence of this JWT cookie, but the middleware logs an error stating that the cookie is not found or the user is not authorized, even though the cookie is clearly present in the browser.

CheckUserJWT.php

namespace App\Http\Middleware;

use Closure;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Support\Facades\Log;

class CheckUserJWT
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // Check if the user JWT cookie exists
        if ($request->hasCookie('user')) {
            $token = $request->cookie('user');

            Log::info("Cookie exists");
            try {
                // Attempt to authenticate the user using the JWT token
                $user = JWTAuth::setToken($token)->authenticate();

                // Check if the user is a regular user
                if ($user && $user->role === 'USER') {
                    return $next($request);
                }
            } catch (JWTException $e) {
                Log::error('JWT Authentication error: ' . $e->getMessage());

                // Handle token expiration or invalid token
                return redirect()->route('login');
            }
        }

        Log::warning('User cookie not found or user is not a regular user.');

        // If the cookie doesn't exist or user is not a regular user, redirect to login
        return redirect()->route('login');
    }
}

The middleware is applied to the user.home route:

Route::middleware(CheckUserJWT::class)->group(function () {
    Route::get('/user/home', function () {
        return view('user.home'); 
    })->name('user.home');
});

Issue:

Even though the JWT token is visible in the browser's Dev Tools under the "Cookies" section, the middleware logs the following warning:

User cookie not found or user is not a regular user.
2
  • is the domain of the cookie same as the api domain? Commented Aug 30, 2024 at 9:48
  • @Joe yes! cookie is found under that domain, in the browser Commented Sep 1, 2024 at 11:15

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.