PHPackages                             makaveli/laravel-jwt-auth - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Framework](/categories/framework)
4. /
5. makaveli/laravel-jwt-auth

ActiveLibrary[Framework](/categories/framework)

makaveli/laravel-jwt-auth
=========================

JWT authentication for Laravel

1.1.5(1mo ago)0101MITPHPPHP ^8.2

Since Apr 27Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/Ma1kaveli/laravel-jwt-auth)[ Packagist](https://packagist.org/packages/makaveli/laravel-jwt-auth)[ RSS](/packages/makaveli-laravel-jwt-auth/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (14)Versions (25)Used By (1)

makaveli/laravel-jwt-auth
=========================

[](#makavelilaravel-jwt-auth)

[![Packagist Version](https://camo.githubusercontent.com/359f5e6c817c02a0e9ba72d86917e2a4dfb3a83a075d7dcf1069ef49dbf52ea5/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d616b6176656c692f6c61726176656c2d6a77742d617574682e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/makaveli/laravel-jwt-auth)[![Packagist Downloads](https://camo.githubusercontent.com/63c27544ee4f8978f5ae2a95483eb83f7d4456e780f96b4959d763f7deb180eb/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d616b6176656c692f6c61726176656c2d6a77742d617574682e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/makaveli/laravel-jwt-auth)[![License](https://camo.githubusercontent.com/942e017bf0672002dd32a857c95d66f28c5900ab541838c6c664442516309c8a/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e7376673f7374796c653d666c61742d737175617265)](LICENSE)

🌍 Languages
-----------

[](#-languages)

- 🇺🇸 English (default)
- 🇷🇺 [Русская версия](docs/ru/README.md)

Table of Contents
-----------------

[](#table-of-contents)

1. [Introduction](#introduction)
2. [Requirements](#requirements)
3. [Installation](#installation)
4. [Configuration](#configuration)
5. [Core Components](#core-components)
    - [JWTAuth Trait](#jwtauth-trait)
    - [Actions](#actions)
    - [Services](#services)
    - [Repositories](#repositories)
    - [Helpers](#helpers)
    - [Token Storage](#token-storage)
6. [Database Schema](#database-schema)
7. [Quick Start](#quick-start)
8. [Integration with BaseRepository](#integration-with-baserepository)
9. [Extending the Package](#extending-the-package)
10. [Console Commands](#console-commands)
11. [Recommendations](#recommendations)
12. [Useful Links](#useful-links)

Introduction
------------

[](#introduction)

**makaveli/laravel-jwt-auth** is a lightweight, self‑contained JWT authentication package for Laravel. It provides generation, verification, refresh, and blacklisting of JWT tokens without relying on external libraries like `tymon/jwt-auth` or `firebase/php-jwt`. The package supports multiple storage drivers for blacklisting (memory, Redis, database) and a variety of algorithms (HS256, RS\*, ES\*), making it both flexible and easy to integrate into any Laravel project.

Key features:

- Generation of access/refresh token pairs.
- Support for HS256 (default), RS\*, ES\* algorithms.
- Automatic signature, header, and payload verification (exp, sub, name).
- Token blacklisting on refresh/logout with configurable TTL.
- Three storage drivers for blacklist: `memory` (Laravel array cache), `redis`, `database`.
- Fully tested with PHPUnit + Orchestra Testbench.
- Console commands to generate JWT secret and run migrations.
- Simple configuration via `config/jwt.php`.

Requirements
------------

[](#requirements)

- PHP 8.2 or higher
- Laravel 10.x, 11.x, or 12.x
- Composer
- (Optional) Redis extension or `predis/predis` for the `redis` driver
- (Optional) Database driver for the `database` driver (SQLite, MySQL, etc.)

Installation
------------

[](#installation)

1. Install the package via Composer:

    ```
    composer require makaveli/laravel-jwt-auth
    ```
2. (Optional) Publish the configuration file to customize settings:

    ```
    php artisan vendor:publish --tag=jwt-config
    ```

    This will copy the configuration file to `config/jwt.php`.
3. Run the package migrations (required only for the `database` driver):

    ```
    php artisan migrate
    ```

    The package automatically loads its migrations; you do not need to publish them.

Configuration
-------------

[](#configuration)

The configuration file `config/jwt.php` allows you to customize the following parameters:

ParameterDescriptionDefault`algo`JWT algorithm (`HS256`, `RS256`, `ES256`, etc.)`'HS256'``private`Secret key (or path to private key for RSA/ECDSA)`env('JWT_SECRET', 'test-secret-key')``ttl`Access token lifetime in minutes`env('JWT_TTL', 60)``refresh_ttl`Refresh token lifetime in minutes`env('JWT_REFRESH_TTL', 120)``allow_infinite_ttl`Allow infinite TTL (token never expires)`false``infinite_ttl_fallback`Fallback TTL in seconds if infinite is not allowed`31536000` (1 year)`sub_payload_field`User model field used for the `sub` claim`'email'``name_payload_fields`User model fields to include in the `name` claim`['name']``user_model`User model class`\Illuminate\Database\Eloquent\Model::class``token_storage.driver`Blacklist storage driver (`memory`, `redis`, `database`)`env('JWT_TOKEN_STORAGE_DRIVER', 'memory')``token_storage.storage_ttl`Blacklist TTL in seconds`env('JWT_BLACKLIST_STORAGE_TTL', 86400 * 7)` (7 days)Example configuration for production:

```
return [
    'algo'                 => env('JWT_ALGO', 'HS256'),
    'private'              => env('JWT_SECRET'),
    'ttl'                  => env('JWT_TTL', 15),
    'refresh_ttl'          => env('JWT_REFRESH_TTL', 10080),
    'allow_infinite_ttl'   => false,
    'infinite_ttl_fallback'=> 31536000,
    'sub_payload_field'    => 'email',
    'name_payload_fields'  => ['name', 'email'],
    'user_model'           => App\Models\User::class,
    'token_storage' => [
        'driver'       => env('JWT_TOKEN_STORAGE_DRIVER', 'redis'),
        'storage_ttl'  => env('JWT_BLACKLIST_STORAGE_TTL', 604800),
    ],
];
```

Recommended `.env` values:

```
JWT_ALGO=HS256
JWT_SECRET=your-very-long-random-secret
JWT_TTL=15
JWT_REFRESH_TTL=10080
JWT_TOKEN_STORAGE_DRIVER=redis
JWT_BLACKLIST_STORAGE_TTL=604800
```

Core Components
---------------

[](#core-components)

### JWTAuth Trait

[](#jwtauth-trait)

The main trait that provides high‑level methods for token operations. It can be used in any class (typically a service or controller). It internally uses the underlying services and repositories.

**Methods:**

- `fromUser($user)`: Generates an access/refresh token pair from a user model.
- `verify($token)`: Verifies a token and returns the payload (or an array with `verify_fail` flag).
- `refreshToken($refreshToken)`: Issues a new token pair using a valid refresh token.
- `logout($accessToken)`: Blacklists the access token.

**Example:**

```
use JWTAuth\JWTAuth;

class AuthService
{
    use JWTAuth;

    public function authenticate($credentials)
    {
        if (auth()->attempt($credentials)) {
            [$access, $refresh] = $this->fromUser(auth()->user());
            return compact('access', 'refresh');
        }
        return null;
    }
}
```

### Actions

[](#actions)

The `Actions` namespace contains classes for blacklist operations:

- `AddToBlacklist`: Adds a token to the blacklist.
- `IsBlacklisted`: Checks if a token is blacklisted.
- `RemoveExpired`: Removes expired tokens from storage (used by the scheduled job).

### Services

[](#services)

Services encapsulate the write operations:

- `BlacklistService`: Manages blacklist writes (used by `AddToBlacklist`).

### Repositories

[](#repositories)

Repositories handle read operations:

- `BlacklistRepository`: Checks if a token is blacklisted (used by `IsBlacklisted`).

### Helpers

[](#helpers)

Low‑level JWT helpers:

- `JWTSlice`: Encodes and decodes the JWT structure (header, payload, signature).
- `JWTVerify`: Verifies the signature and payload integrity.
- `JWTCoder`: Handles encoding/decoding with the chosen algorithm.

### Token Storage

[](#token-storage)

The blacklist storage is abstracted behind `TokenStorageInterface`. Three implementations are provided:

DriverStorageBest for`memory`Laravel `ArrayStore`Testing, development`redis`Redis (setex + scan)Production (recommended)`database`Table `blacklisted_tokens`When Redis is not availableSwitching drivers is done via `config/jwt.php` or the environment variable `JWT_TOKEN_STORAGE_DRIVER`.

Database Schema
---------------

[](#database-schema)

When the `database` driver is used, the package creates the table `blacklisted_tokens` (or the name defined in the migration) with the following structure:

ColumnTypeDescription`id`bigint (PK)Auto‑increment ID`token`stringThe JWT token (or its hash)`expires_at`timestampToken expiration time (used for cleanup)`created_at`timestampWhen it was blacklistedThe table is automatically created when you run the Laravel migrations.

Quick Start
-----------

[](#quick-start)

### 1. Configure the package

[](#1-configure-the-package)

Publish and edit `config/jwt.php` to set your secret, TTLs, and storage driver. Generate a strong secret:

```
php artisan jwt:secret
```

### 2. Create an authentication service

[](#2-create-an-authentication-service)

```
use JWTAuth\JWTAuth;
use App\Models\User;

class AuthService
{
    use JWTAuth;

    public function login($email, $password)
    {
        $user = User::where('email', $email)->first();
        if (!$user || !password_verify($password, $user->password)) {
            return null;
        }

        [$access, $refresh] = $this->fromUser($user);
        return compact('access', 'refresh');
    }
}
```

### 3. Use the tokens in your controller

[](#3-use-the-tokens-in-your-controller)

```
class AuthController extends Controller
{
    protected $authService;

    public function __construct(AuthService $authService)
    {
        $this->authService = $authService;
    }

    public function login(Request $request)
    {
        $tokens = $this->authService->login($request->email, $request->password);
        if (!$tokens) {
            return response()->json(['message' => 'Invalid credentials'], 401);
        }
        return response()->json($tokens);
    }

    public function refresh(Request $request)
    {
        $newTokens = $this->authService->refreshToken($request->refresh_token);
        if (!$newTokens) {
            return response()->json(['message' => 'Invalid refresh token'], 401);
        }
        return response()->json($newTokens);
    }

    public function logout(Request $request)
    {
        $this->authService->logout($request->bearerToken());
        return response()->json(['message' => 'Logged out']);
    }
}
```

### 4. Protect routes with middleware

[](#4-protect-routes-with-middleware)

Create a middleware that verifies the access token and attaches the user to the request.

```
namespace App\Http\Middleware;

use Closure;
use JWTAuth\JWTAuth;

class JwtAuthMiddleware
{
    use JWTAuth;

    public function handle($request, Closure $next)
    {
        $token = $request->bearerToken();
        if (!$token) {
            return response()->json(['message' => 'Token missing'], 401);
        }

        $payload = $this->verify($token);
        if ($payload['verify_fail'] ?? false) {
            return response()->json(['message' => 'Invalid or expired token'], 401);
        }

        $request->merge(['jwt_user' => $payload['user']]);
        return $next($request);
    }
}
```

Integration with BaseRepository
-------------------------------

[](#integration-with-baserepository)

While this package does not directly depend on `makaveli/laravel-core`, you can easily use it in your existing repository architecture. For example, you might inject the `JWTAuth` trait into a repository that handles authentication‑related data.

```
use JWTAuth\JWTAuth;

class AuthRepository
{
    use JWTAuth;

    public function createTokensForUser($user)
    {
        return $this->fromUser($user);
    }
}
```

This keeps the token logic inside the repository, following the same pattern as other `makaveli` packages.

Extending the Package
---------------------

[](#extending-the-package)

You can extend the package in several ways:

- **New storage driver**: Implement `JWTAuth\Interfaces\TokenStorageInterface` and register it in `TokenStorageFactory`.
- **Different algorithm**: Extend `JWTSlice` and `JWTAlgo` to support custom signing methods.
- **Custom payload fields**: Override the `getJWTPayload` method in your own trait or service to add custom claims.
- **Audit logging**: Use Laravel events or observers on the `BlacklistedToken` model (if using the database driver) to log token blacklist events.

Console Commands
----------------

[](#console-commands)

CommandDescription`php artisan jwt:secret`Generates a new random secret key and updates the `.env` file.`php artisan jwt:clear-tokens`Removes expired tokens from the blacklist (should be scheduled daily).To schedule the cleanup, add the following to `App\Console\Kernel`:

```
protected function schedule(Schedule $schedule)
{
    $schedule->command('jwt:clear-tokens')->daily();
}
```

Recommendations
---------------

[](#recommendations)

- **Use a strong, random secret** and rotate it occasionally.
- **Choose the appropriate storage driver** – `redis` is recommended for production, `database` if you don’t have Redis.
- **Keep access token TTL short** (e.g., 15 minutes) for security, and refresh token TTL longer (e.g., 7 days).
- **Always validate the `sub` claim** and compare it with the actual user in your database.
- **Implement token revocation** (logout) by blacklisting the access token.
- **Schedule the token cleanup** to keep your blacklist storage lean.

Useful Links
------------

[](#useful-links)

- Package repository:
- Dependencies:
    - [makaveli/laravel-core](https://github.com/Ma1kaveli/laravel-core) (optional, but recommended)
    - [makaveli/laravel-query-builder](https://github.com/Ma1kaveli/laravel-query-builder) (optional)

###  Health Score

44

—

FairBetter than 92% of packages

Maintenance91

Actively maintained with recent releases

Popularity7

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity59

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~14 days

Recently: every ~21 days

Total

24

Last Release

45d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/ed91cef75c6ac70dbc36843a28453115d78996faf342c9d0f86d89283b751522?d=identicon)[Ma1kaveli](/maintainers/Ma1kaveli)

---

Top Contributors

[![Ma1kaveli](https://avatars.githubusercontent.com/u/74207027?v=4)](https://github.com/Ma1kaveli "Ma1kaveli (26 commits)")

---

Tags

frameworklaravel

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/makaveli-laravel-jwt-auth/health.svg)

```
[![Health](https://phpackages.com/badges/makaveli-laravel-jwt-auth/health.svg)](https://phpackages.com/packages/makaveli-laravel-jwt-auth)
```

###  Alternatives

[codewithdennis/larament

Larament is a time-saving starter kit to quickly launch Laravel 13.x projects. It includes FilamentPHP 5.x pre-installed and configured, along with additional tools and features to streamline your development workflow.

3691.5k](/packages/codewithdennis-larament)[kompo/kompo

Laravel &amp; Vue.js FullStack Components for Rapid Application Development

11812.4k21](/packages/kompo-kompo)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
