DEV Community

Cover image for Laravel 8 - Using JWT(JSON Web Token) in REST API πŸ”₯πŸ”₯πŸ”₯
DaleLanto
DaleLanto

Posted on • Updated on

Laravel 8 - Using JWT(JSON Web Token) in REST API πŸ”₯πŸ”₯πŸ”₯

Json Web Token or (JWT) is a URL-safe method or a JSON Payload for securely transferring information from one party to another in the form of Json object.

It is a method to encode claims in a JSON document and becoming a famous way of handling auth.

APIs use tokens to validate users and do not maintain session state between the requests.

Now that we have enough knowledge to get started, let’s create a fresh laravel project!

#1 Install Laravel
Open terminal and run the following command to install laravel 8 app:
composer create-project --prefer-dist laravel/laravel blog

#2 Configure Database
Navigate root directory of your installed laravel restful authentication api with jwt tutorial project.

Open .env file. Then add the database details as follow:

 DB_CONNECTION=mysql 
 DB_HOST=127.0.0.1 
 DB_PORT=3306 
 DB_DATABASE=here your database name here
 DB_USERNAME=here database username here
 DB_PASSWORD=here database password here
Enter fullscreen mode Exit fullscreen mode

#3 Install JWT Auth
Open terminal and install composer require tymon/jwt-auth package
composer require tymon/jwt-auth

After successfully installing laravel jwt, let us register providers.

Open config/app.php . and put the bellow code :

(Add service provider for Laravel 5.4 or below,
Add the service provider to the providers array)

'providers' => [

    ...

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

Publish the config

Run the following command to publish the package config file:

php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
Enter fullscreen mode Exit fullscreen mode

Generate secret key

php artisan jwt:secret

#4 Registering Middleware

JWT auth package comes up with middlewares that we can use. Register auth.jwt middleware in

app/Http/Kernel.php

protected $routeMiddleware = [
    'auth.jwt' => 'auth.jwt' => 'Tymon\JWTAuth\Middleware\GetUserFromToken',
];
Enter fullscreen mode Exit fullscreen mode

#5 Run Migration
Open terminal and migrate:
php artisan migrate

#6 Create APIs Route
In this step, you need to create rest API routes for laravel restful authentication apis with jwt project.

So, navigate to the routes directory and open api.php. Then update the following routes into api.php file:

use App\Http\Controllers\API\JWTAuthController;

Route::post('register', [JWTAuthController::class, 'register']);
Route::post('login', [JWTAuthController::class, 'login']);
Route::group(['middleware' => 'auth.jwt'], function () {
    Route::post('logout', [JWTAuthController::class, 'logout']);
});
Enter fullscreen mode Exit fullscreen mode

#7 Create JWT Auth Controller
Open terminal and do :
php artisan make:controller Api\JWTAuthController

After that, you need to create some methods in JWTAuthController.php.

Let's navigate to app/http/controllers/API directory and open JWTAuthController.php file.

After that, update the following methods into your JWTAuthController.php file:

<?php

namespace App\Http\Controllers\API;

use JWTAuth;
use Validator;
use App\Models\User;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;
use Symfony\Component\HttpFoundation\Response;

class JwtAuthController extends Controller
{
    public $token = true;

    public function register(Request $request)
    {

         $validator = Validator::make($request->all(), 
                      [ 
                      'name' => 'required',
                      'email' => 'required|email',
                      'password' => 'required',  
                      'c_password' => 'required|same:password', 
                     ]);  

         if ($validator->fails()) {  

               return response()->json(['error'=>$validator->errors()], 401); 

            }   


        $user = new User();
        $user->name = $request->name;
        $user->email = $request->email;
        $user->password = bcrypt($request->password);
        $user->save();

        if ($this->token) {
            return $this->login($request);
        }

        return response()->json([
            'success' => true,
            'data' => $user
        ], Response::HTTP_OK);
    }

    public function login(Request $request)
    {
        $input = $request->only('email', 'password');
        $jwt_token = null;

        if (!$jwt_token = JWTAuth::attempt($input)) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid Email or Password',
            ], Response::HTTP_UNAUTHORIZED);
        }

        return response()->json([
            'success' => true,
            'token' => $jwt_token,
        ]);
    }

    public function logout(Request $request)
    {
        $this->validate($request, [
            'token' => 'required'
        ]);

        try {
            JWTAuth::invalidate($request->token);

            return response()->json([
                'success' => true,
                'message' => 'User logged out successfully'
            ]);
        } catch (JWTException $exception) {
            return response()->json([
                'success' => false,
                'message' => 'Sorry, the user cannot be logged out'
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }

    public function getUser(Request $request)
    {
        $this->validate($request, [
            'token' => 'required'
        ]);

        $user = JWTAuth::authenticate($request->token);

        return response()->json(['user' => $user]);
    }
}
Enter fullscreen mode Exit fullscreen mode

To run the app lets open terminal and do:
php artisan serve

#8 Test API with JWT in Postman

Look at the image below to call laravel 8 restful API with jwt authentication.

Input your own information - name, email and password.

Laravel Register Rest API with JWT:

Image description

Now you can login to the API:

Image description

Finally to getUser API. Go to postman and change the url to ../getUser/id then click on Auth->Bearer Token paste the token generated from the login in the token input and the users data will appear!

Hurray! you have successfully created a simple REST API with JWT! Hope this helped you!

Top comments (0)