Laravel 8 REST API with JWT Authentication

Laravel 8 Rest api authentication with jwt auth example. In this post, i will show you how to build rest api authentication using jwt auth in laravel 8 using tymondesigns/jwt-auth.

As well as learn how to get refresh token with jwt auth in laravel 8.

In this example, i will create login, registration, logout, refresh access token and get user info apis using jwt authentication in laravel 8 using tymondesigns/jwt-auth.

JWT Authentication In Laravel 8

  • Step 1 – Installing Laravel 8 App
  • Step 2 – Database Configuration
  • Step 3 – Installing JWT
  • Step 4 – Configure JWT
  • Step 5 – Run Migration
  • Step 6 – Create jwt Auth Routes
  • Step 7 – Creating JWT Auth API Controller
  • Step 8 – Start Development Server
  • Step 9 – Test Laravel 8 JWT Authentication API with Postman

Step 1 – Installing Laravel 8 App

In step 1, open your terminal and navigate to your local web server directory using the following command:

//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html

Then install laravel 8 latest application using the following command:

composer create-project --prefer-dist laravel/laravel LaravelJWTAuth

Step 2 – Database Configuration

In step 2, open your downloaded laravel 8 app into any text editor. Then find .env file and configure database detail like following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password

Step 3 – Installing JWT

In step 3, Navigate to your downloaded LaravelJWTAuth directory. And then install JWT Auth Packages in your laravel 8. Open terminal and run the following command:

cd / LaravelJWTAuth

composer require tymon/jwt-auth

Next, register and aliases and Providers in auth.php file, which is located inside config directory:

'providers' => [
     ...
    /*
     * Package Service Providers...
     */

    'Tymon\JWTAuth\Providers\LaravelServiceProvider'


    /*
     * Application Service Providers...
     */
     ...

],
'aliases' => [
    ...
    'JWTAuth' => 'Tymon\JWTAuth\Facades\JWTAuth',
    'JWTFactory' => 'Tymon\JWTAuth\Facades\JWTFactory'
],

Next, run the following command to publish jwt auth package:

php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"

Finally, let’s generate a secret key that this package will use to encrypt our tokens:

php artisan jwt:secret

Step 4 – Configure JWT

In step 4, configure jwt package in laravel app.

So, open app/User.php file and include HasApiTokens trait inside the User model, as mentioned below:

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

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

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

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


    /**
     * 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 [];
    }
}

Now, Configure driver for the JWT AUTH. So open auth.php, which is located inside config directory and add the following code into it:

  'defaults' => [
        'guard' => 'api',
        'passwords' => 'users',
    ],

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
            'hash' => false,
        ],
    ],

Step 5 – Run Migration

Now, open again your terminal and type the following command on cmd to create tables into your selected database:

php artisan migrate

Step 6 – Create JWT Auth Routes

In step 6, open your api.php file, which is located inside routes directory. Then add the following routes into web.php file:

<?php

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\API\JWTAuthController;


Route::group([
    'middleware' => 'api',
    'prefix' => 'auth'

], function ($router) {

    Route::post('register', [JWTAuthController::class, 'register']);
    Route::post('login', [JWTAuthController::class, 'login']);
    Route::post('logout', [JWTAuthController::class, 'logout']);
    Route::post('refresh', [JWTAuthController::class, 'refresh']);
    Route::get('user-profile', [JWTAuthController::class, 'userProfile'];
});

Step 7 – Creating JWT Auth API Controller

In step 7, create jwt authentication controller file controller by using the following command:

php artisan make:controller API\JWTAuthController

The above command will create AuthController.php file, which is located inside LaravelJWTAuth/app/Http/Controllers/API directory. So add the following code into it:

<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Auth;

use Validator;

use Illuminate\Http\Request;

use App\Models\User;

class JWTAuthController extends Controller
{
    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login', 'register']]);
    }

    /**
     * Register a User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|between:2,100',
            'email' => 'required|email|unique:users|max:50',
            'password' => 'required|confirmed|string|min:6',
        ]);

        $user = User::create(array_merge(
                    $validator->validated(),
                    ['password' => bcrypt($request->password)]
                ));

        return response()->json([
            'message' => 'Successfully registered',
            'user' => $user
        ], 201);
    }

    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
    	$validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required|string|min:6',
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors(), 422);
        }

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

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

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function profile()
    {
        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->createNewToken(auth()->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function createNewToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 60
        ]);
    }
}

Step 8 – Start Development Server

In step 8, open your command prompt again and run the following command to start development server for your laravel 8 jwt auth:

php artisan serve

Step 9 – Test Laravel 8 JWT Authentication API with Postman

Now, open postman app and call laravel 8 rest api with JWT auth app.

I have called login,registration logout, profile and refresh token jwt auth apis on Postman app, it looks like:

Authentication APIs for Login, Register, User Profile, Token Refresh and Logout.

MethodEndpoint
POST/api/auth/register
POST/api/auth/login
GET/api/auth/user-profile
POST/api/auth/refresh
POST/api/auth/logout

User Registration API in Laravel

User Login JWT api Laravel

User Profile JWT API Laravel

Note that, you need to pass "Authorization: Bearer Token" for User Profile, Token Refresh, and Logout REST APIs:

JWT Token Refresh in Laravel

User Logout JWT Api Laravel

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *