Install JWT in Laravel app
Hello Coders, In this story I will be showing you how to implement the JWT authentication system in our Laravel App.
Let’s begin with creating a new Laravel app for this,we will need to create a new app in the terminal:
$ composer create-project laravel/laravel jwt-laravel
$ cd jwt-laravel
To Implement JWT we need to install the jwt-auth package.
$ composer require tymon/jwt-auth
Important: if you are using Laravel 5.4 or below Add the service provider to the providers
array in the config/app.php
config file as follows:
'providers' => [
...
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
]
Publish the config
After adding providers next step is to Run the following command to publish the package config file:
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
You should now have a config/jwt.php
file that allows you to configure the basics of this package.
Generate secret key
I have included a helper command to generate a key for you:
php artisan jwt:secret
This will update your .env
file with something like JWT_SECRET=secret-key
After completing the above steps let’s move to the next steps which are crucial for generating token for our users, we need to update the user model for that.
<?php
namespace App;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements JWTSubject
{
use Notifiable;
// Rest omitted for brevity
/**
* Get the identifier that will be stored in the subject claim of the JWT.
*
* @return mixed
*/
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* @return array
*/
public function getJWTCustomClaims()
{
return [];
}
}
Configure Auth guard
Inside the config/auth.php
file you will need to make a few changes to configure Laravel to use the jwt
guard to power your application authentication.
Make the following changes to the file:
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
...
'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
Here we are telling the api
guard to use the jwt
driver and we are setting the api
guard as the default.
Add Authenticated routes
now add auth routes inside the “routes/api.php” file:
<?php
// routes/api.php
use App\Http\Controllers\AuthController;
Route::group([
'middleware' => 'api',
'prefix' => 'auth'
], function ($router) {
Route::post('login', [AuthController::class, 'login']);
Route::post('logout', [AuthController::class, 'logout']);
Route::post('refresh', [AuthController::class, 'refresh');
Route::post('me', [AuthController::class, 'me']);
});
Create the AuthController
Then create the AuthController
, either manually or by running the artisan command:
php artisan make:controller AuthController
Then add the following:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
class AuthController extends Controller
{
/**
* Create a new AuthController instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login']]);
}
/**
* Get a JWT via given credentials.
*
* @return \Illuminate\Http\JsonResponse
*/
public function login()
{
$credentials = request(['email', 'password']);
if (! $token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
/**
* Get the authenticated User.
*
* @return \Illuminate\Http\JsonResponse
*/
public function me()
{
return response()->json(auth()->user());
}
/**
* Log the user out (Invalidate the token).
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout()
{
auth()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
/**
* Refresh a token.
*
* @return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken(auth()->refresh());
}
/**
* Get the token array structure.
*
* @param string $token
*
* @return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60
]);
}
}
After all these steps it’s time to test the API and must receive a token in response You should now be able to POST to the login endpoint (e.g. http://example.dev/auth/login
) with some valid credentials and see a response like:
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ",
"token_type": "bearer",
"expires_in": 3600
}
Some More advanced usage that is useful in the app
Adding custom claims
$token = auth()->claims(['foo' => 'bar'])->attempt($credentials);
Set the token explicitly
$user = auth()->setToken('eyJhb...')->user();
Set the request instance explicitly
$user = auth()->setRequest($request)->user();
Override the token ttl
$token = auth()->setTTL(7200)->attempt($credentials);
Conclusion
You have successfully tested a ready-made solution for authorizing JWT tokens in your application. You can now use it for your client application and API. I appreciate you reading.
If you find this Story Helpful, You can show some support to help me.
you can avoid this step if you already have your app ready.