Laravel 10 jwt auth using tymon/jwt-auth
Tags: laravel, jwt, auth, php
Published: 2023-04-02 15:15:34

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


Add following to config/app.php:
```php
'aliases' => Facade::defaultAliases()->merge([
        'Jwt' => Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
        'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class,
        'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
    ])->toArray(),
```
Can also add the following in the providers array:
```php
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
```

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:
```php
'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
        ],
```

Now create some routes in routes/api.php
```php
Route::middleware(['api'])->group(function() {
    Route::post('/login', [AuthController::class, 'login']);
    Route::post('/register', [AuthController::class, 'register']);
    Route::get('/getaccount, [AuthController::class, 'getaccount']);
});
```

Modify the Users model to use the jwt functionalities:
```php
<?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 [];
    }
}

```

Lastly modify the AuthController:
```php
<?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
        ]);
    }
}

```


login response:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o9p67qhxqesl45n51iji.png)


register response:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ybnxzr2x8vg5u8b7s5e3.png)

getaccount reponse:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/stte8i330097tnsc3ol5.png)

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. :smiley: