Gagan Sandhu

Full Stack Developer and ML Enthusiast

The Simple & Efficient Way to Enable JWT auth in Laravel By Using PHP-JWT Module

I encounter this issue while working on an application for a client recently. Instead of using a JWT library build for Laravel, I used firebase/php-jwt to generate and authenticate users. Don’t ask why as there were many reasons behind this decision. If you are using any Laravel library for JWT like tymondesigns/jwt-auth then you don’t need this anyway, use the library if you want.
But think about it, every extra library you add to your application is making it slower. If you can’t find any solid reason to use any library, don’t use it.
The very first thing I did which is kind of stupid was to verify the token inside each route directly by decoding the token etc. The firebase JWT's way of doing things. Don't’ judge me, the application is going to have only ten routes at max. But the Laravel’s web-sockets authenticate process is all done behind the scenes.
We can provide custom middleware implementation for authentication routes I know and trust me I tried it but couldn't get it working for some reason. So I found this solution somewhere on the forums while searching the web.



1. AuthServiceProvider.php

Auth::viaRequest('custom-jwt', function ($request) {
    $token = $request->bearerToken();
    $secret = config('auth.auth_jwt_secret_key');

    if ($token && strlen($token) > 0) {
        try {
            $user = JWT::decode($token, $secret, array("HS256"));
            if (!$user) throw new \Exception;
        } catch (\Exception $e) {
            return null;
        }

        return DB::table("users")->where("id", $user->user->id)->first();
    }

    return null;
});
Add this code in the boot method of AuthServiceProvider.php

2. Update the API guard

Update the API guard driver to custom-jwt in
config/auth.php
After this, you can access your authenticated user inside your Laravel app by simply calling Auth::user().
That's it. I have no idea why people want to use libraries for such simple tasks and compromise their website performance.
This solution is not for those who using passport in their application as Laravel has an inbuilt system to support that. Use this only if you have a custom JWT implementation.
I hope this helps someone. Thank you.


Tags

More by Gagan Sandhu

Topics of interest