PHPackages                             iqbalatma/laravel-jwt-authentication - 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. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. iqbalatma/laravel-jwt-authentication

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

iqbalatma/laravel-jwt-authentication
====================================

5.0.0(1mo ago)5219PHPPHP ^8.3

Since Oct 29Pushed 1mo ago1 watchersCompare

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

READMEChangelog (10)Dependencies (9)Versions (43)Used By (0)

Laravel JWT Authentication
==========================

[](#laravel-jwt-authentication)

This is authentication for Laravel with JWT Based. Inspired by [tymondesigns/jwt-auth](https://github.com/tymondesigns/jwt-auth#documentation) and [PHP-Open-Source-Saver/jwt-auth](https://github.com/PHP-Open-Source-Saver/jwt-auth). This site was built using package from [firebase/php-jwt](https://github.com/firebase/php-jwt) for encode and decode JWT.

---

How To Install
--------------

[](#how-to-install)

This package using syntax and feature that only available on ***php version at least 8.0***

### Install Via Composer

[](#install-via-composer)

```
composer require iqbalatma/laravel-jwt-authentication
```

### Publishing Asset

[](#publishing-asset)

You can publish asset for customization using this command

```
php artisan vendor:publish --provider='Iqbalatma\LaravelJwtAuthentication\LaravelJWTAuthenticationProvider'
```

### Implement JWTSubject

[](#implement-jwtsubject)

You need to implement Iqbalatma\\LaravelJwtAuthentication\\Interfaces\\JWTSubject on User model. If you would like to add another additional data on jwt claim, you can return array on getJWTCustomClaims

```
use Iqbalatma\LaravelJwtAuthentication\Interfaces\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
    public function getJWTIdentifier(): string|int
    {
        return $this->getKey();
    }

    public function getJWTCustomClaims(): array
    {
        return [];
    }
}
```

### Generate JWT Credentials

[](#generate-jwt-credentials)

This credential is used for sign jwt token and make sure the token is valid

```
php artisan jwt:secret
```

or using pairs of public and secret key

```
php artisan jwt:generate-certs
```

### Configuration config/auth.php

[](#configuration-configauthphp)

```
'defaults' => [
    'guard' => 'jwt',
    'passwords' => 'users',
],

'guards' => [
    ...
    "jwt" => [
        "driver" => "jwt",
        "provider" => "users"
    ]
],
```

---

Configuration config/jwt.php
----------------------------

[](#configuration-configjwtphp)

Jwt signin using public and private key is first priority, so if you define private and public key, jwt will be signing using this key pairs. But if you do not define private and public key, jwt will use secret key for signing. If two type key does not exists, it will throw an error.

Note

Here is available algorithm if you're using secret key

- HS512
- HS256
- HS384
- HS224

Note

Here is available algorithm if you're using pairs of public and private key

- RS512
- RS256
- RS384
- ES384
- ES256
- ES256K

```
return [
    /*
    |--------------------------------------------------------------------------
    | JWT library guard
    |--------------------------------------------------------------------------
    |
    | This is guard that set in auth, because inside library guard defined manually
    | Auth::guard(config("jwt.guard"));
    |
    */
    "guard" => "jwt",

    /*
    |--------------------------------------------------------------------------
    | Access token verifier
    |--------------------------------------------------------------------------
    |
    | This is configuration to prevent xss attack by verified access token via cookie httpOnly
    |
    */
    "is_using_access_token_verifier" => true,

    /*
    |--------------------------------------------------------------------------
    | JWT Sign in Algorithm
    |--------------------------------------------------------------------------
    |
    | Algorithm for sign jwt token. This token is using encoder and decoder from
    | https://github.com/firebase/php-jwt
    |
    */
    'algo' => env('JWT_ALGO', 'HS256'),

    /*
    |--------------------------------------------------------------------------
    | JWT Private Key
    |--------------------------------------------------------------------------
    |
    | This private key use for first priority of encoding and decoding jwt (signing)
    | so if this key (private key) and (public key) exists, jwt will sign using
    | this key pairs as first priority. If this key pairs does not exist, sign jwt will
    | using jwt secret. If secret does not exist it will throw an error
    |
    */
    "jwt_private_key" => env("JWT_PRIVATE_KEY", null),

    /*
    |--------------------------------------------------------------------------
    | JWT Public Key
    |--------------------------------------------------------------------------
    |
    | This public key is part of key pairs for signing jwt token.
    |
    */
    "jwt_public_key" => env("JWT_PUBLIC_KEY", null),

    /*
    |--------------------------------------------------------------------------
    | JWT Passphrase
    |--------------------------------------------------------------------------
    |
    | This is passphrase use to get jwt private key that translate the key
    | using this passphrase
    |
    */
    "jwt_passphrase" => env("JWT_PASSPHRASE", null),

    /*
    |--------------------------------------------------------------------------
    | Secret
    |--------------------------------------------------------------------------
    |
    | This is secret that used for encoding jwt. This secret use to validate signature
    | Do not expose this jwt secret
    |
    */
    'secret' => env('JWT_SECRET', null),

    /*
    |--------------------------------------------------------------------------
    | Access Token TTL
    |--------------------------------------------------------------------------
    |
    | This is TTL (Time To Life) for access token. When token is expired, the token
    | is already invalid. Access token using to access protected resource.
    | Middleware that can accept this token is auth.jwt:access
    | This TTL is in seconds
    | Default 1 Hour
    |
    */
    'access_token_ttl' => env('JWT_TTL', 60 * 60),

    /*
    |--------------------------------------------------------------------------
    | Refresh Token TTL
    |--------------------------------------------------------------------------
    |
    | This is TTL (Time To Life) for refresh token. When token is expired, the token
    | is already invalid. Refresh token using to regenerate access token and refresh token
    | and revoke previous access token and refresh token.
    | Middleware that can accept this token is auth.jwt:refresh
    | This TTL is in seconds
    | Default 7 Days
    */
    'refresh_token_ttl' => env('JWT_REFRESH_TTL', 60 * 60 * 24 * 7),

    /*
    |--------------------------------------------------------------------------
    | Refresh Token
    |--------------------------------------------------------------------------
    |
    | Refresh token mechanism is how middleware check/get your refresh token
    | there are two options (cookie / header)
    |
    |
    | Refresh token key is key to get when middleware mechanism choose cookie, so this key
    | is used to get cookie to set refresh token
    |
    */
    'refresh_token' => [
        'key' => 'jwt_refresh_token',
        'http_only' => true,
        'path' => "/",
        'domain' => null,
        'secure' => true,
        'same_site' => 'lax',
    ],

    /*
    |--------------------------------------------------------------------------
    | Access Token Verifier
    |--------------------------------------------------------------------------
    |
    | Access token verifier is used to prevent XSS attack by binding access token
    | to this verifier, and make sure any stolen token cannot be used by attacker
    |
    |
    */
    'access_token_verifier' => [
        'key' => 'access_token_verifier',
        'http_only' => true,
        'path' => "/",
        'domain' => null,
        'secure' => true,
        'same_site' => 'lax',
    ]
];
```

---

How to use middleware ?
-----------------------

[](#how-to-use-middleware-)

When you are doing authentication, you will receive 2 types token, access and refresh. Access token use to get protected resource, for example get data product, add new data user, etc. Access token has shorter ttl, so when access token expired, you can regenerate new token with refresh token. Endpoint that do refresh token must be protected by middleware type refresh. You can see the example on how to implement this middleware bellow

```
use Illuminate\Support\Facades\Route;

//jwt middleware that need refresh token
Route::post("refresh-token", function (){
    //do refresh logic here
})->middleware("auth.jwt:REFRESH");

//jwt middleware that need access token
Route::middleware("auth.jwt:ACCESS")->group(function () {
    Route::get("user", function () {
        return response()->json([
            "success" => true,
            "user" => Auth::user()
        ]);
    });

    // and others route
});
```

---

How to use ?
------------

[](#how-to-use-)

Here is some available method for authentication

### Authenticate User

[](#authenticate-user)

This feature used for validate credentials from user request and return back access\_token and refresh\_token

```
use Illuminate\Support\Facades\Auth;

$credentials = [
    "email" => "admin@mail.com",
    "password" => "admin"
];

#this attempt method will return boolean when user validation success
Auth::attempt($credentials, true, true);
#first parameter for credential, second parameter to tell that authentication using cookie httpOnly, third parameter to get

#if you are using access token verifier by is_using_access_token_verifier = true, its mean you need to set
#access token in cookie httpOnly
return response()->json([
    "access_token" => "...",
])->withCookie(getCreatedCookieAccessTokenVerifier("put your access token verifier here"));

#full example
public function authenticate(AuthenticateRequest $request): JsonResponse
{
    $credentials = request(['username', 'password']);
    if (!$token = Auth::attempt($credentials)) {
        return response()->json(
            ["message" => "Invalid credentials."]
        );
    }

    /** @var User $user */
    $user = Auth::user();
    /** @var User $user */
    $user = Auth::user();
    return response()->json(
        [
            "code" => "SUCCESS",
            "message" => "Logged in successfully.",
            "timestamp" => now(),
            "payload" => [
                "data" => [
                    "id" => $user->id,
                    "username" => $user->username,
                    "first_name" => $user->first_name,
                    "last_name" => $user->last_name,
                    "email" => $user->email,
                    "access_token" => Auth::getAccessToken(),
                ],
            ],
        ]
    )
        ->withCookie(getCreatedCookieAccessTokenVerifier(Auth::getAccessTokenVerifier()))
        ->withCookie(getCreatedCookieRefreshToken(Auth::getRefreshToken()));
}

public function refresh(): JsonResponse
{
    Auth::refreshToken(Auth::user());

    /** @var User $user */
    $user = Auth::user();
    return response()->json(
        [
            "code" => "SUCCESS",
            "message" => "Logged in successfully.",
            "timestamp" => now(),
            "payload" => [
                "data" => [
                    "id" => $user->id,
                    "username" => $user->username,
                    "first_name" => $user->first_name,
                    "last_name" => $user->last_name,
                    "email" => $user->email,
                    "access_token" => Auth::getAccessToken()
                ],
            ],
        ]
    )
        ->withCookie(getCreatedCookieAccessTokenVerifier(Auth::getAccessTokenVerifier()))
        ->withCookie(getCreatedCookieRefreshToken(Auth::getRefreshToken()));
}
```

### Logout User

[](#logout-user)

This feature used for invalidate and blacklist current authorization token

```
use Illuminate\Support\Facades\Auth;

Auth::logout();
Auth::logout(true); #add parameter true for revoke both token pair (access and refresh)
```

### Refresh Token

[](#refresh-token)

This feature used for invalidate access\_token and refresh\_token and invoke new access\_token and refresh\_token

```
use Illuminate\Support\Facades\Auth;

Auth::refreshToken(Auth::user());
```

### Login By System

[](#login-by-system)

This method use for login existing user via authenticable instance

```
use Illuminate\Support\Facades\Auth;
use App\Models\User;

$user = User::find(1);

Auth::login($user);
```

### Get Token

[](#get-token)

After login or attempt method triggered and successfully, you can get token access and refresh via guard instance

```
use Illuminate\Support\Facades\Auth;
use App\Models\User;

$credentials = [
    "email" => "admin@mail.com",
    "password" => "admin"
];

$user = User::query()->where("email", "admin@mail.com")->find();
Auth::attempt($credentials);
Auth::login($user);

Auth::getAccessToken(); #to get access token
Auth::getRefreshToken(); #to get refresh token
Auth::getAccessTokenVerifier(); #to get access token verifier

#if you are not using default guard, you need to specify the guard
Auth::guard("jwt")->getAccessToken();
```

###  Health Score

51

—

FairBetter than 96% of packages

Maintenance91

Actively maintained with recent releases

Popularity19

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity70

Established project with proven stability

 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 ~25 days

Recently: every ~52 days

Total

36

Last Release

45d ago

Major Versions

1.5.0 → 2.0.02025-03-28

2.2.2 → 3.0.02025-07-11

3.5.2 → 4.0.02025-10-11

4.2.0 → 5.0.02026-03-29

PHP version history (2 changes)1.4.8PHP ^8.2

2.0.0PHP ^8.3

### Community

Maintainers

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

---

Top Contributors

[![iqbalatma](https://avatars.githubusercontent.com/u/35129050?v=4)](https://github.com/iqbalatma "iqbalatma (103 commits)")

### Embed Badge

![Health badge](/badges/iqbalatma-laravel-jwt-authentication/health.svg)

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

###  Alternatives

[tymon/jwt-auth

JSON Web Token Authentication for Laravel and Lumen

11.5k49.1M350](/packages/tymon-jwt-auth)[laravel/passport

Laravel Passport provides OAuth2 server support to Laravel.

3.4k85.0M532](/packages/laravel-passport)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9682.1M97](/packages/roots-acorn)[php-open-source-saver/jwt-auth

JSON Web Token Authentication for Laravel and Lumen

8359.8M53](/packages/php-open-source-saver-jwt-auth)[laravel/pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.

1.7k12.1M99](/packages/laravel-pulse)[laragear/two-factor

On-premises 2FA Authentication for out-of-the-box.

339785.3k8](/packages/laragear-two-factor)

PHPackages © 2026

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