Implementing JWT Authentication API in Laravel

This guide walks through installing the tymon/jwt-auth package, configuring Laravel, creating middleware for CORS and JWT verification, defining API routes, building an authentication controller, and testing the registration and login endpoints using tools like Postman or AJAX.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Implementing JWT Authentication API in Laravel

In Laravel, JWT (JSON Web Token) can be used to create user authentication APIs that support front‑end/back‑end separation.

(1) Install the tymon/jwt-auth component

composer require tymon/jwt-auth

Update config/app.php to add the service provider and facade:

'providers' => [
    // ...
    'Tymon\JWTAuth\Providers\JWTAuthServiceProvider',
],
'aliases' => [
    // ...
    'JWTAuth' => 'Tymon\JWTAuth\Facades\JWTAuth',
];

Publish the JWT configuration file to adjust token expiration and other settings:

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

Generate the JWT secret key:

php artisan jwt:generate

(2) Create API routes

Add the following routes to app/Http/routes.php. The group uses the api middleware and a custom checkUserAuth middleware for CORS handling.

Route::group(['middleware' => ['api','checkUserAuth'], 'prefix' => 'api'], function () {
    Route::post('register', 'APIController@register');
    Route::post('login', 'APIController@login');
    Route::group(['middleware' => 'jwt-auth'], function () {
        Route::post('get_user_details', 'APIController@get_user_details');
    });
});

(3) Create the checkUserAuth middleware

This middleware adds CORS headers to allow cross‑origin requests. php artisan make:middleware checkUserAuth Implement it in app/Http/Middleware/checkUserAuth.php:

namespace App\Http\Middleware;
use Closure;
class checkUserAuth {
    public function handle($request, Closure $next) {
        header('Access-Control-Allow-Origin: *');
        $headers = [
            'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin',
        ];
        if ($request->getMethod() == "OPTIONS") {
            return Response::make('OK', 200, $headers);
        }
        $response = $next($request);
        foreach ($headers as $key => $value) {
            $response->header($key, $value);
        }
        return $response;
    }
}

Register the middleware in app/Http/Kernel.php:

protected $routeMiddleware = [
    // ...
    'checkUserAuth' => \App\Http\Middleware\checkUserAuth::class,
];

(4) Create the JWT authentication middleware

php artisan make:middleware authJWT

Implementation in app/Http/Middleware/authJWT.php:

namespace App\Http\Middleware;
use Closure;
use JWTAuth;
use Exception;
class authJWT {
    public function handle($request, Closure $next) {
        try {
            $user = JWTAuth::toUser($request->input('token'));
        } catch (Exception $e) {
            if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException) {
                return response()->json(['error' => 'Token is Invalid']);
            } elseif ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException) {
                return response()->json(['error' => 'Token is Expired']);
            } else {
                return response()->json(['error' => 'Something is wrong']);
            }
        }
        return $next($request);
    }
}

Register it in app/Http/Kernel.php:

protected $routeMiddleware = [
    // ...
    'jwt-auth' => \App\Http\Middleware\authJWT::class,
];

(5) Create the controller

In app/Http/Controllers/APIController.php define registration, login and user‑detail methods:

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Hash;
use JWTAuth;
class APIController extends Controller {
    public function register(Request $request) {
        $input = $request->all();
        $input['password'] = Hash::make($input['password']);
        User::create($input);
        return response()->json(['result' => true]);
    }
    public function login(Request $request) {
        $input = $request->all();
        if (!$token = JWTAuth::attempt($input)) {
            return response()->json(['result' => 'wrong email or password.']);
        }
        return response()->json(['result' => $token]);
    }
    public function get_user_details(Request $request) {
        $input = $request->all();
        $user = JWTAuth::toUser($input['token']);
        return response()->json(['result' => $user]);
    }
}

(6) Front‑end testing

Use tools such as Postman, REST client, or AJAX to test the endpoints. Example AJAX calls:

$.ajax({
  url: "http://xxx.com/api/register",
  dataType: "json",
  type: "POST",
  data: {"name":"HD","email":"[email protected]","password":"123456"},
  success: function (data) { alert("user created successfully"); }
});

$.ajax({
  url: "http://xxx.com/api/login",
  dataType: "json",
  type: "POST",
  data: {"email":"[email protected]","password":"123456"},
  success: function (data) { alert(data.result); }
});

This completes a full JWT‑based authentication API setup in Laravel.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendAuthenticationPHPAPIJWTLaravel
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.