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

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

devkit2026/laravel-jwt-auth
===========================

A standalone JWT authentication module for Laravel.

v0.0.5(5mo ago)010MITPHPPHP ^8.2

Since Dec 2Pushed 5mo agoCompare

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

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

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

[](#laravel-jwt-authentication-package)

A standalone, reusable JWT authentication package for Laravel with email verification, refresh token rotation, and flexible configuration options.

Features
--------

[](#features)

- ✅ JWT-based authentication (access + refresh tokens)
- ✅ User registration with email verification
- ✅ Refresh token rotation for enhanced security
- ✅ Configurable refresh token delivery (cookie or body)
- ✅ Flexible authenticated user return type (Laravel model or DTO)
- ✅ Standardized error responses
- ✅ Event-driven architecture
- ✅ Comprehensive test coverage

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

[](#installation)

### 1. Install via Composer

[](#1-install-via-composer)

```
composer require devkit2026/laravel-jwt-auth
```

### 2. Publish Configuration and Migrations

[](#2-publish-configuration-and-migrations)

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

### 3. Run Migrations

[](#3-run-migrations)

```
php artisan migrate
```

### 4. Generate JWT Secret

[](#4-generate-jwt-secret)

Generate a secure JWT secret key:

```
php artisan jwt:secret
```

This command will:

- Generate a random 32-character base64-encoded secret
- Add it to your `.env` file as `JWT_SECRET`
- Warn you if a secret already exists (use `--force` to override)

**Options:**

- `--show` - Display the generated key without modifying files
- `--force` - Force the operation even if a key already exists

### 5. Configure Environment Variables

[](#5-configure-environment-variables)

Add the following to your `.env` file (JWT\_SECRET will be set by the `jwt:secret` command):

```
# JWT Secret (generated by php artisan jwt:secret)
JWT_SECRET=base64:...

# JWT Algorithm (default: HS256)
JWT_ALGO=HS256

# Token TTL (in minutes)
JWT_ACCESS_TTL=60
JWT_REFRESH_TTL=43200

# Refresh token delivery method: 'cookie' or 'body'
JWT_REFRESH_METHOD=cookie

# Authenticated user return type: 'dto' or 'model'
JWT_AUTH_USER_TYPE=dto

# User model (optional, defaults to App\Models\User)
JWT_USER_MODEL=App\Models\User

# Mail configuration (for email verification)
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=your-email@gmail.com
MAIL_PASSWORD=your-app-password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=your-email@gmail.com
MAIL_FROM_NAME="${APP_NAME}"
```

Configuration Options
---------------------

[](#configuration-options)

### Refresh Token Delivery Method

[](#refresh-token-delivery-method)

Choose how refresh tokens are delivered to clients:

- **`cookie`** (default): Refresh token sent as httpOnly cookie (more secure)
- **`body`**: Refresh token included in JSON response body

```
JWT_REFRESH_METHOD=cookie  # or 'body'
```

### Authenticated User Type

[](#authenticated-user-type)

Choose what type of user object is returned:

- **`dto`** (default): Returns a UserDto with id, email, role, and additional data
- **`model`**: Returns the full Laravel User model

```
JWT_AUTH_USER_TYPE=dto  # or 'model'
```

API Endpoints
-------------

[](#api-endpoints)

### 1. Register

[](#1-register)

**POST** `/api/auth/register`

**Request:**

```
{
  "email": "user@example.com",
  "password": "Password123!",
  "password_confirmation": "Password123!"
}
```

**Response (201):**

```
{
  "message": "User registered successfully. Please verify your email.",
  "user": {
    "id": 1,
    "email": "user@example.com"
  }
}
```

### 2. Verify Email

[](#2-verify-email)

**GET** `/api/auth/verify/{id}/{hash}?signature=...`

Clicking the link in the verification email will verify the user's email address.

**Response (200):**

```
{
  "message": "Email verified successfully."
}
```

### 3. Login

[](#3-login)

**POST** `/api/auth/login`

**Request:**

```
{
  "email": "user@example.com",
  "password": "Password123!"
}
```

**Response (200) - Cookie Method:**

```
{
  "access_token": "eyJhbGciOi...",
  "token_type": "bearer",
  "expires_in": 3600,
  "user": {
    "id": 1,
    "email": "user@example.com",
    "role": null
  }
}
```

*Refresh token sent as httpOnly cookie*

**Response (200) - Body Method:**

```
{
  "access_token": "eyJhbGciOi...",
  "refresh_token": "LLqWAEmHhq6eg467...",
  "token_type": "bearer",
  "expires_in": 3600,
  "user": {
    "id": 1,
    "email": "user@example.com",
    "role": null
  }
}
```

### 4. Refresh Token

[](#4-refresh-token)

**POST** `/api/auth/refresh`

**Request (Cookie Method):**No body required, refresh token read from cookie.

**Request (Body Method):**

```
{
  "refresh_token": "LLqWAEmHhq6eg467..."
}
```

**Response (200):**

```
{
  "access_token": "new.jwt.token",
  "token_type": "bearer",
  "expires_in": 3600,
  "user": {
    "id": 1,
    "email": "user@example.com"
  }
}
```

### 5. Logout

[](#5-logout)

**POST** `/api/auth/logout`

**Request (Cookie Method):**No body required.

**Request (Body Method):**

```
{
  "refresh_token": "LLqWAEmHhq6eg467..."
}
```

**Response (200):**

```
{
  "message": "Logged out successfully"
}
```

### 6. Get Authenticated User

[](#6-get-authenticated-user)

**GET** `/api/auth/me`

**Headers:**

```
Authorization: Bearer {access_token}

```

**Response (200):**

```
{
  "user": {
    "id": 1,
    "email": "user@example.com",
    "role": null
  }
}
```

Protecting Routes
-----------------

[](#protecting-routes)

Use the `jwt.auth` middleware to protect your routes:

```
Route::middleware('jwt.auth')->group(function () {
    Route::get('/protected', function (Request $request) {
        return response()->json([
            'user' => $request->user()
        ]);
    });
});
```

Error Codes
-----------

[](#error-codes)

The package returns standardized error responses:

CodeHTTP StatusDescription`ERR_VALIDATION`422Validation error`ERR_INVALID_CREDENTIALS`401Invalid email or password`ERR_EMAIL_NOT_VERIFIED`403Email not verified`ERR_ACCESS_TOKEN_EXPIRED`401Access token expired`ERR_REFRESH_TOKEN_EXPIRED`401Refresh token expired`ERR_REFRESH_TOKEN_REVOKED`401Refresh token revoked`ERR_TOKEN_INVALID`401Invalid token`ERR_TOKEN_MISSING`401Token not provided`ERR_USER_NOT_FOUND`404User not found**Error Response Format:**

```
{
  "error": {
    "code": "ERR_INVALID_CREDENTIALS",
    "message": "Invalid email or password."
  }
}
```

Testing
-------

[](#testing)

The package includes comprehensive tests. To run them:

```
cd packages/Devkit2026/laravel-jwt-auth
composer install
./vendor/bin/phpunit
```

Security Considerations
-----------------------

[](#security-considerations)

1. **JWT Secret**: Use a strong, random secret key (at least 32 characters)
2. **Refresh Tokens**: Stored as hashed values in the database
3. **Token Rotation**: Refresh tokens are automatically rotated on use
4. **HttpOnly Cookies**: When using cookie method, refresh tokens are httpOnly and secure
5. **Email Verification**: Users must verify their email before logging in

Events
------

[](#events)

The package dispatches the following events:

- `UserRegistered`: Fired when a user registers
- `Verified`: Fired when email is verified (Laravel's built-in event)

Customization
-------------

[](#customization)

### Custom User Model

[](#custom-user-model)

Specify a custom user model in your `.env`:

```
JWT_USER_MODEL=App\Models\CustomUser
```

Your user model must:

- Have `email` and `password` fields
- Implement `MustVerifyEmail` contract (optional, for email verification)

### Extending UserDto

[](#extending-userdto)

You can add additional fields to the UserDto by modifying the `payload_fields` in `config/jwt_auth.php`:

```
'payload_fields' => ['user_id', 'user_role', 'custom_field'],
```

License
-------

[](#license)

MIT

Support
-------

[](#support)

For issues, questions, or contributions, please visit the GitHub repository.

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance72

Regular maintenance activity

Popularity5

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity41

Maturing project, gaining track record

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

Total

5

Last Release

157d ago

PHP version history (2 changes)v0.0.1PHP ^8.1

v0.0.2PHP ^8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/60cce146b8ef97f57da9cc86a90f6fd49713bef69863a658c73bee0da3f3b7fe?d=identicon)[KiazimKhutaba](/maintainers/KiazimKhutaba)

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[laravel/passport

Laravel Passport provides OAuth2 server support to Laravel.

3.4k85.0M529](/packages/laravel-passport)[tymon/jwt-auth

JSON Web Token Authentication for Laravel and Lumen

11.5k49.1M344](/packages/tymon-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)[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.8M52](/packages/php-open-source-saver-jwt-auth)[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)
