laravel-jwt-auth maintained by cyan-wings
Laravel JWT Auth (dual token)
English | 简体中文
Short-lived access token + long-lived, revocable refresh token authentication for Laravel 12 / 13.
Unlike tymon/jwt-auth, the two token types use separate secrets and are managed as a lifecycle: refresh
tokens are stored hashed, rotated on every use, and a replayed (already used/revoked) refresh token
revokes the whole token family once the reuse grace window has passed.
Requirements
- PHP >= 8.2 (Laravel 13 requires PHP >= 8.3)
- Laravel 12 or 13
- Database (default) or Redis for refresh token storage
Installation
# 1. Install the package
composer require cyan-wings/laravel-jwt-auth
# 2. Publish the config and migration (both are required; the package does not auto-load them)
php artisan vendor:publish --tag=jwt-auth
# ...or publish only the config / only the migration
php artisan vendor:publish --tag=jwt-auth-config
php artisan vendor:publish --tag=jwt-auth-migrations
# 3. Run the migration (creates the refresh_tokens table)
php artisan migrate
# 4. Generate JWT_ACCESS_SECRET / JWT_REFRESH_SECRET and write them into .env
# (it asks before overwriting existing secrets)
php artisan jwt-auth:secrets
# ...or overwrite without confirmation
php artisan jwt-auth:secrets --force
# 5. Rebuild the config cache after changing .env / config values (e.g. in production)
php artisan config:cache
Notes:
jwt-auth:secretsfails if.envdoes not exist.- When
.env.exampleexists, it ensures the empty keysJWT_ACCESS_SECRET=,JWT_REFRESH_SECRET=,JWT_ACCESS_TTL=andJWT_REFRESH_TTL=are present, without duplicating existing keys. - If the config is not published, any token operation throws a
ConfigurationExceptiontelling you to publish it. - Token lifetimes are configurable via
JWT_ACCESS_TTLandJWT_REFRESH_TTL(seconds). Leaving them empty falls back to the defaults (900/1209600).
Configure a guard in config/auth.php:
'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
api is just an example name — use whatever guard name your app defines (e.g. order). If your app's
default guard is not a JWT guard, set JWT_AUTH_GUARD or pass the guard name explicitly to
JwtAuth::attempt() / fromUser().
The model used to issue tokens (e.g. User) must implement CyanWings\LaravelJwtAuth\Contracts\JWTSubject:
use CyanWings\LaravelJwtAuth\Contracts\JWTSubject;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements JWTSubject
{
public function getJWTIdentifier(): int|string
{
return $this->getKey();
}
/** @return array<string, mixed> */
public function getJWTCustomClaims(): array
{
return []; // extra claims merged into issued access tokens
}
}
Multiple guards / models
Each guard resolves its own provider, so you can authenticate different models (e.g. User and Admin):
'guards' => [
'api' => ['driver' => 'jwt', 'provider' => 'users'],
'admin' => ['driver' => 'jwt', 'provider' => 'admins'],
],
'providers' => [
'users' => ['driver' => 'eloquent', 'model' => App\Models\User::class],
'admins' => ['driver' => 'eloquent', 'model' => App\Models\Admin::class],
],
Tokens carry a provider claim, and a guard only accepts tokens issued for its own provider. This prevents an
Admin token from being treated as a User with the same id. Both models must implement JWTSubject.
Guard names are arbitrary — api and admin are just examples. A guard named order configured the same
way works identically, e.g. Auth::guard('order')->login($order) or JwtAuth::fromUser($order, 'order').
Single sign-on (one session per guard)
Enable one active session per guard:
JWT_SINGLE_SIGN_ON=true
JWT_SINGLE_SIGN_ON_GUARDS=api,admin
When enabled, a successful login on one of the listed guards revokes the previous sessions of that guard only; other guards are unaffected. Already-issued access tokens from the old session are rejected too, because their token family is no longer active. Guards that are not listed keep normal multi-session behaviour.
Usage
use CyanWings\LaravelJwtAuth\Facades\JwtAuth;
// Login: validate credentials and issue a pair.
$pair = JwtAuth::attempt(['email' => $request->email, 'password' => $request->password]);
if ($pair === null) {
return response()->json(['message' => 'Invalid credentials'], 401);
}
return response()->json($pair->toArray());
// { token_type, access_token, expires_in, refresh_token, refresh_expires_in }
// Issue tokens for an already authenticated user.
$pair = JwtAuth::fromUser($user);
// Multi-guard: pass the guard name explicitly.
$pair = JwtAuth::attempt(['email' => $admin->email, 'password' => $request->password], 'admin');
$pair = JwtAuth::fromUser($admin, 'admin');
// Refresh: consumes the presented token and rotates it.
$pair = JwtAuth::refresh($request->input('refresh_token'));
// Logout: revoke the whole token family.
JwtAuth::revoke($request->input('refresh_token'));
// Revoke every session of a user (password change, ban, ...).
JwtAuth::revokeAll($user);
Login through the guard
You can also call attempt() on the guard itself. It returns false on invalid credentials, or an array
with the tokens and their lifetimes on success:
use Illuminate\Support\Facades\Auth;
$tokens = Auth::guard('api')->attempt([
'email' => $request->input('email'),
'password' => $request->input('password'),
]);
if ($tokens === false) {
return response()->json(['message' => 'Invalid credentials'], 401);
}
return response()->json($tokens);
// { token_type, access_token, expires_in, refresh_token, refresh_expires_in }
// Any credential fields supported by the provider work, e.g. phone:
$tokens = Auth::guard('api')->attempt([
'phone' => $request->input('phone'),
'password' => $request->input('password'),
]);
If you have already resolved and verified the model, log it in directly:
$tokens = Auth::guard('api')->login($user);
The model must belong to the guard's provider; logging an Admin into the api guard throws a
ConfigurationException.
Protect routes with the built-in Laravel auth middleware:
Route::middleware('auth:api')->get('/me', fn () => request()->user());
Response format
{
"token_type": "Bearer",
"access_token": "eyJ...",
"expires_in": 900,
"refresh_token": "eyJ...",
"refresh_expires_in": 1209600
}
Configuration
All options live in config/jwt-auth.php (publish it first). Options that have an .env name can be
overridden from .env; keys marked — are config-file only and must be edited in
config/jwt-auth.php.
After changing .env or the config file, run php artisan config:clear (or config:cache in production).
Tokens
| Config key | .env |
Default | Meaning |
|---|---|---|---|
jwt-auth.access.secret |
JWT_ACCESS_SECRET |
— | HMAC secret for access tokens. Required, must differ from the refresh secret. |
jwt-auth.access.ttl |
JWT_ACCESS_TTL |
900 |
Access token lifetime in seconds. Empty value uses the default. |
jwt-auth.refresh.secret |
JWT_REFRESH_SECRET |
— | HMAC secret for refresh tokens. Required, must differ from the access secret. |
jwt-auth.refresh.ttl |
JWT_REFRESH_TTL |
1209600 |
Refresh token lifetime in seconds (14 days). |
jwt-auth.refresh.reuse_grace_ttl |
JWT_REUSE_GRACE_TTL |
10 |
Grace window (seconds) in which a just-rotated refresh token may be replayed and receive the same replacement. 0 disables it. |
Signing and claims
| Config key | .env |
Default | Meaning |
|---|---|---|---|
jwt-auth.access.algo |
— | HS256 |
Access token HMAC algorithm. Allowed: HS256, HS384, HS512. |
jwt-auth.refresh.algo |
— | HS256 |
Refresh token HMAC algorithm. Allowed: HS256, HS384, HS512. |
jwt-auth.access.leeway |
JWT_LEEWAY |
30 |
Clock-skew tolerance in seconds for access tokens. |
jwt-auth.refresh.leeway |
JWT_LEEWAY |
30 |
Clock-skew tolerance in seconds for refresh tokens. |
jwt-auth.access.issuer |
JWT_ISSUER |
— | Optional iss claim added to access tokens. |
jwt-auth.refresh.issuer |
JWT_ISSUER |
— | Optional iss claim added to refresh tokens. |
Guard and provider
| Config key | .env |
Default | Meaning |
|---|---|---|---|
jwt-auth.guard |
JWT_AUTH_GUARD |
app default, if it is a jwt guard | Guard used by the JwtAuth manager when no guard is passed explicitly. |
jwt-auth.provider |
JWT_AUTH_PROVIDER |
— | Optional default provider used only when issuing directly through TokenService without a guard. |
Single sign-on
| Config key | .env |
Default | Meaning |
|---|---|---|---|
jwt-auth.single_sign_on.enabled |
JWT_SINGLE_SIGN_ON |
false |
Keep only one active session per listed guard. |
jwt-auth.single_sign_on.guards |
JWT_SINGLE_SIGN_ON_GUARDS |
— | Comma-separated guard names that enforce single sign-on, e.g. api,admin. |
Storage
| Config key | .env |
Default | Meaning |
|---|---|---|---|
jwt-auth.storage.driver |
JWT_AUTH_STORAGE |
database |
Refresh token store: database or redis. |
jwt-auth.storage.connection |
JWT_AUTH_STORAGE_CONNECTION |
default connection | Database connection used by the database driver. |
jwt-auth.storage.table |
— | refresh_tokens |
Table used by the database driver. |
jwt-auth.storage.redis_connection |
JWT_AUTH_REDIS_CONNECTION |
default connection | Redis connection (from config/database.php) used by the redis driver. |
jwt-auth.storage.prefix |
— | jwt_auth: |
Key prefix used by the redis driver. |
Note: the redis driver uses your Laravel Redis configuration (config/database.php → redis), including
REDIS_CLIENT, REDIS_HOST, REDIS_PORT, REDIS_PASSWORD, REDIS_DB.
Example .env
# Required: two different secrets
JWT_ACCESS_SECRET=
JWT_REFRESH_SECRET=
# Token lifetimes (seconds)
JWT_ACCESS_TTL=900
JWT_REFRESH_TTL=1209600
JWT_REUSE_GRACE_TTL=10
# Optional: guard used by JwtAuth when none is passed
JWT_AUTH_GUARD=api
# Optional: only for direct TokenService usage without a guard
JWT_AUTH_PROVIDER=users
# Single sign-on (one active session per listed guard)
JWT_SINGLE_SIGN_ON=false
JWT_SINGLE_SIGN_ON_GUARDS=
# Storage: database or redis
JWT_AUTH_STORAGE=database
JWT_AUTH_STORAGE_CONNECTION=
JWT_AUTH_REDIS_CONNECTION=
# Optional: clock-skew tolerance and issuer (applies to both token types)
JWT_LEEWAY=30
JWT_ISSUER=
Security model
- Access and refresh tokens are signed with different secrets and carry a
token_useclaim; a token can never be used as the other type. - Tokens carry
guardandproviderclaims; a guard rejects tokens issued for a different guard or provider, preventing cross-model identity collisions. - Only HMAC algorithms (
HS256/HS384/HS512) are accepted, preventing algorithm confusion. - Refresh tokens are stored hashed (SHA-256); the stored fingerprint is compared with
hash_equals. - Rotation + reuse detection: replaying a used or revoked token after the grace window revokes its whole family.
- Grace window: within
reuse_grace_ttlseconds a rotated token may be replayed (concurrent requests, client retries) and receives the same replacement refresh token instead of invalidating the family. After the window, replay is treated as reuse. Set the TTL to0to disable it. - On the database driver, consuming the old token and inserting the new one run in a single transaction, so a storage failure rolls back and leaves the old token usable (fail-safe).
sub,jti,token_use,provider,iat,expare mandatory; clock skew is configurable vialeeway.- Stateless access tokens cannot be revoked individually — keep their TTL short and revoke the refresh family when a session must end.
Security
Please report vulnerabilities privately — see SECURITY.md. The current self-audit checklist and automated-check results are in docs/security-audit.md. The package has not yet had a formal third-party audit.
Redis driver notes
The Redis driver stores each refresh token in its own key with a TTL, plus small marker keys for
used/revoked state and sets for family/user indexes. TTLs mirror the refresh token lifetime, so Redis
performs the cleanup; prune() is a no-op.
Rotation is performed by a single Lua script, so consuming the old token and writing the replacement happen atomically in one round trip. The keys are not hash-tagged, so on a Redis Cluster all keys involved in a rotation must live in the same slot; for clustered deployments prefer the database driver or run the refresh storage on a dedicated single-node Redis.
Maintenance (database driver)
Expired refresh token records are not deleted automatically. Schedule the prune command:
// routes/console.php (Laravel 11+) or your console kernel
$schedule->command('jwt-auth:prune')->daily();
# Delete records that have already expired (default)
php artisan jwt-auth:prune
# Keep a 7-day audit window past expiry
php artisan jwt-auth:prune --days=7
# Tune the delete batch size (default 1000)
php artisan jwt-auth:prune --chunk=500
The Redis driver stores tokens with a TTL, so jwt-auth:prune is a no-op there.
Testing
composer test # phpunit
composer analyse # phpstan
composer cs # php-cs-fixer (dry run)
License
MIT.