DEV Community

Debajyoti Das
Debajyoti Das

Posted on • Updated on

Laravel 10 jwt auth using tymon/jwt-auth

Firstly install Laravel then install the tymon package:
composer require tymon/jwt-auth

Add following to config/app.php:

'aliases' => Facade::defaultAliases()->merge([
        'Jwt' => Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
        'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class,
        'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
    ])->toArray(),
Enter fullscreen mode Exit fullscreen mode

Can also add the following in the providers array:

Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
Enter fullscreen mode Exit fullscreen mode

Now publish the necessary files:
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"

Run the migrations:
php artisan migrate

Generate a jwt token, will get saved in .env
php artisan jwt:secret

Add the following to the api array in the guards array:

'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
        ],
Enter fullscreen mode Exit fullscreen mode

Now create some routes in routes/api.php

Route::middleware(['api'])->group(function() {
    Route::post('/login', [AuthController::class, 'login']);
    Route::post('/register', [AuthController::class, 'register']);
    Route::get('/getaccount, [AuthController::class, 'getaccount']);
});
Enter fullscreen mode Exit fullscreen mode

Modify the Users model to use the jwt functionalities:

<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    public function getJWTCustomClaims()
    {
        return [];
    }
}

Enter fullscreen mode Exit fullscreen mode

Lastly modify the AuthController:

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use JWTAuth;

use Illuminate\Http\Request;

class AuthController extends Controller
{
    //
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login', 'register']]);//login, register methods won't go through the api guard
    }
    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required',
            'password' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json($validator->errors(), 422);
        }

        if (! $token = auth()->attempt($validator->validated())) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        return $this->respondWithToken($token);
    }

    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|between:2,100',
            'email' => 'required|string|email|max:100|unique:users',
            'password' => 'required|string|confirmed|min:6',
        ]);
        if($validator->fails()){
            return response()->json($validator->errors()->toJson(), 400);
        }

        $user = User::create([
            'name' => $request->get('name'),
            'email' => $request->get('email'),
            'password' => Hash::make($request->get('password')),
        ]);

        $token = JWTAuth::fromUser($user);

        return response()->json([
            'message' => 'User successfully registered',
            'user' => $user,
            'token' => $token,
        ], 200);
    }

    public function getaccount()
    {
        return response()->json(auth()->user());
    }


    public function logout()
    {
        auth()->logout();

        return response()->json(['message' => 'Successfully logged out']);
    }
    public function refresh()
    {
        return $this->respondWithToken(auth()->refresh());
    }
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth('api')->factory()->getTTL() * 60 //mention the guard name inside the auth fn
        ]);
    }
}

Enter fullscreen mode Exit fullscreen mode

login response:

Image description

register response:

Image description

getaccount reponse:

Image description

For knowing more about the package check the documentation:
https://jwt-auth.readthedocs.io/en/develop/auth-guard/

All of the above code has been tried and tested on Laravel 10.0,
Do drop a Like if it has helped you. 😃

Top comments (1)

Collapse
 
fabrizzioalco profile image
fabrizzioalco

Why does the response on the token is "true"? Shouldn't this return the bearer token to be used when log in?