PHPackages                             huseynvsal/jwt-auth-refresh - 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. huseynvsal/jwt-auth-refresh

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

huseynvsal/jwt-auth-refresh
===========================

A Laravel package for JWT authentication with access and refresh tokens.

1.0.2(1y ago)353MITPHPPHP &gt;=8.0

Since Feb 11Pushed 1y ago1 watchersCompare

[ Source](https://github.com/huseynvsal/jwt-auth-refresh)[ Packagist](https://packagist.org/packages/huseynvsal/jwt-auth-refresh)[ RSS](/packages/huseynvsal-jwt-auth-refresh/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (6)Versions (4)Used By (0)

JWT Auth Refresh Package
========================

[](#jwt-auth-refresh-package)

This Laravel package provides JWT authentication with access and refresh token functionality. It includes all the necessary logic for token generation, token refresh, and user logout without the need to write any complex controller or middleware.

Features
--------

[](#features)

- **JWT Access and Refresh Tokens**: Generate access and refresh tokens during login.
- **Token Refresh**: Refresh tokens if the refresh token is valid.
- **Logout**: Remove all refresh tokens during logout.
- **Custom Guards**: Automatically registers a custom JWT guard.
- **Configuration**: Easily configure token expiration times and secret keys.

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

[](#installation)

### Step 1: Install the Package

[](#step-1-install-the-package)

Install the package using Composer.

```
composer require huseynvsal/jwt-auth-refresh
```

### Step 2: Publish Resources

[](#step-2-publish-resources)

After installing the package, you need to publish the configuration and migration files.

Run the following command to publish the resources:

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

This will publish:

- `config/jwt-auth.php` – The configuration file for JWT tokens (secret keys and expiration times).
- A migration file to create `refresh_tokens` tables.

### Step 3: Run Migrations

[](#step-3-run-migrations)

Run the migration to create the necessary table for storing refresh tokens.

```
php artisan migrate
```

### Step 4: Configure `.env` File

[](#step-4-configure-env-file)

In your .env file, add the following configuration for JWT tokens:

```
JWT_SECRET_KEY=your-secret-key-here
JWT_REFRESH_SECRET_KEY=your-refresh-secret-key-here
JWT_ACCESS_TOKEN_EXPIRATION=3600  # 1 hour
JWT_REFRESH_TOKEN_EXPIRATION=604800  # 7 days
```

- `JWT_SECRET_KEY`: The secret key used to sign JWT tokens. Ensure you keep it secure.
- `JWT_SECRET_KEY`: The secret key used to sign refresh tokens. Ensure you keep it secure.
- `JWT_ACCESS_TOKEN_EXPIRATION`: The expiration time for access tokens (in seconds).
- `JWT_REFRESH_TOKEN_EXPIRATION`: The expiration time for refresh tokens (in seconds).

### Step 5: Set Guard in `config/auth.php`

[](#step-5-set-guard-in-configauthphp)

Your package will automatically register the custom jwt guard for authentication. The next step is to set it in the config/auth.php file.

Ensure that your config/auth.php is configured to use the jwt guard for API authentication.

```
// config/auth.php

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

    'api' => [
        'driver' => 'jwt',
        'provider' => 'users'
    ]
]
```

This sets the default guard for API requests to use the custom jwt guard provided by the package.

### Step 6: Update User Model (Optional)

[](#step-6-update-user-model-optional)

If you want to use the JWT-based authentication with your own `User` model, ensure that your User model implements `Illuminate\Contracts\Auth\Authenticatable` and have `refreshTokens` relation defined:

Example:

```
// app/Models/User.php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Huseynvsal\JwtAuthRefresh\Models\AccessToken;
use Huseynvsal\JwtAuthRefresh\Models\RefreshToken;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    public function refreshTokens(): HasMany
    {
        return $this->hasMany(RefreshToken::class, 'user_id');
    }

    // Additional user logic...
}
```

This is required so that Laravel can authenticate the user using the JWT guard.

---

Usage
-----

[](#usage)

### Step 1: Login and Generate Tokens

[](#step-1-login-and-generate-tokens)

In your `AuthController`, you can use the `JwtAuthService` to generate both the access and refresh tokens when the user logs in.

Example login method:

```
// app/Http/Controllers/AuthController.php

namespace App\Http\Controllers;

use App\Models\Customer;
use Huseynvsal\JwtAuthRefresh\Exceptions\InvalidTokenException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Huseynvsal\JwtAuthRefresh\Services\JwtAuthService;

class AuthController extends Controller
{
    protected JwtAuthService $jwtAuthService;

    public function __construct(JwtAuthService $jwtAuthService)
    {
        $this->jwtAuthService = $jwtAuthService;
    }

    public function login(): JsonResponse
    {
        $user = User::find(1);

        $accessToken = $this->jwtAuthService->generateAccessToken($user);
        $refreshToken = $this->jwtAuthService->generateRefreshToken($user);

        return response()->json([
            'accessToken' => $accessToken,
            'refreshToken' => $refreshToken
        ]);
    }
}
```

### Step 2: Refresh Tokens

[](#step-2-refresh-tokens)

You can create an API to allow users to refresh their tokens using a valid refresh token.

Example refresh method:

```
// app/Http/Controllers/AuthController.php

public function refresh(Request $request): JsonResponse
{
    try
    {
        $tokens = $this->jwtAuthService->refreshTokens($request->input('refreshToken'));

        return response()->json($tokens);
    }
    catch (InvalidTokenException $e)
    {
        return response()->json(['error' => $e->getMessage()], 401);
    }
}
```

### Step 3: Logout and Revoke Tokens

[](#step-3-logout-and-revoke-tokens)

To handle logout, you can delete the user's access and refresh tokens:

```
// app/Http/Controllers/AuthController.php

public function logout(): JsonResponse
{
    $user = auth()->user();
    $this->jwtAuthService->revokeTokensForUser($user);

    return response()->json(['message' => 'Logged out successfully']);
}
```

---

Additional Information
----------------------

[](#additional-information)

- **JWT Tokens:** The refresh tokens will be stored in the refresh\_tokens tables.
- **Guard Usage:** The jwt guard is automatically registered, and you can use the auth() helper to authenticate users using JWT tokens in your controllers.
- **Expiration:** Both access and refresh tokens have configurable expiration times defined in the config/jwt-auth.php file.

###  Health Score

28

—

LowBetter than 51% of packages

Maintenance38

Infrequent updates — may be unmaintained

Popularity12

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity46

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

Total

3

Last Release

539d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/61144551?v=4)[Vüsal](/maintainers/huseynvsal)[@huseynvsal](https://github.com/huseynvsal)

---

Top Contributors

[![huseynvsal](https://avatars.githubusercontent.com/u/61144551?v=4)](https://github.com/huseynvsal "huseynvsal (6 commits)")

### Embed Badge

![Health badge](/badges/huseynvsal-jwt-auth-refresh/health.svg)

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

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3345.4M354](/packages/psalm-plugin-laravel)[spatie/laravel-permission

Permission handling for Laravel 12 and up

13.0k107.5M1.6k](/packages/spatie-laravel-permission)[api-platform/laravel

API Platform support for Laravel

58190.1k21](/packages/api-platform-laravel)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

265.2k](/packages/aedart-athenaeum)[pressbooks/pressbooks

Pressbooks is an open source book publishing tool built on a WordPress multisite platform. Pressbooks outputs books in multiple formats, including PDF, EPUB, web, and a variety of XML flavours, using a theming/templating system, driven by CSS.

45844.8k1](/packages/pressbooks-pressbooks)[illuminate/auth

The Illuminate Auth package.

9328.5M1.4k](/packages/illuminate-auth)

PHPackages © 2026

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