Installation:
composer require nikservik/laravel-jwt-auth
php artisan vendor:publish --provider="Nikservik\LaravelJwtAuth\LaravelJwtAuthServiceProvider" --tag=migrations
php artisan migrate
jwt_users table exists (checks for id, name, email, password, remember_token, api_token, token_expires_at).First Use Case:
use Nikservik\LaravelJwtAuth\Facades\JwtAuth;
$user = JwtAuth::register([
'name' => 'Test User',
'email' => 'test@example.com',
'password' => 'password123',
]);
$token = JwtAuth::attempt(['email' => 'test@example.com', 'password' => 'password123']);
app/Http/Kernel.php:
'api' => [
\Nikservik\LaravelJwtAuth\Http\Middleware\VerifyJwtToken::class,
],
Then protect routes:
Route::middleware(['api'])->group(function () {
Route::get('/protected', function () {
return response()->json(['message' => 'Protected route']);
});
});
User Management:
JwtAuth::register() with validated input. Extend the JwtUser model if custom fields are needed.// Login
$token = JwtAuth::attempt($credentials);
// Logout (revoke token)
JwtAuth::logout();
$refreshedToken = JwtAuth::refresh($oldToken);
Protected Routes:
public function __construct() {
$this->middleware('api');
}
public function protectedRoute() {
$user = JwtAuth::user(); // Returns the authenticated JwtUser model
}
Custom Claims: Add metadata to tokens (e.g., roles):
$token = JwtAuth::fromUser($user, [
'role' => 'admin',
'is_active' => true
]);
Laravel Sanctum/Passport:
Use alongside Sanctum for session-based auth or Passport for OAuth2. Avoid mixing token storage (e.g., don’t store JWTs in Sanctum’s personal_access_tokens table).
Rate Limiting:
Combine with Laravel’s throttle middleware to limit JWT-authenticated requests:
Route::middleware(['api', 'throttle:60,1'])->group(...);
Testing:
Use JwtAuth::setToken($token) in tests to simulate authentication:
$this->actingAs(JwtAuth::user(), 'api');
Token Storage:
jwt_users table (api_token and token_expires_at). Never store sensitive data in these fields. Use custom claims for metadata instead.Migration Conflicts:
users table, the jwt_users migration might fail. Manually adjust the migration or drop the table and republish:
php artisan migrate:fresh --env=testing
Password Hashing:
App\User model (or JwtUser) uses Laravel’s HasApiTokens trait and Notifiable. The package assumes BCrypt hashing via Laravel’s Hash facade.Token Expiry:
.env:
JWT_TTL=3600 # 1 hour in seconds
Token Validation Errors:
TokenInvalidException or TokenExpiredException. Log the raw error:
try {
$user = JwtAuth::parseToken()->authenticate();
} catch (\Nikservik\LaravelJwtAuth\Exceptions\TokenExpiredException $e) {
Log::error('Token expired: ' . $e->getMessage());
}
Middleware Bypass:
Kernel.php.api middleware group.auth:api middleware conflicts (this package uses api by default).Locale/Translation Issues:
php artisan vendor:publish --tag=translations
resources/lang/{locale}/jwt.php.Custom User Model:
JwtUser model (published in app/Models/JwtUser.php after publishing views):
class CustomUser extends JwtUser {
protected $fillable = ['custom_field'];
}
AuthServiceProvider:
public function boot() {
$this->app['Nikservik\LaravelJwtAuth\JwtAuth']->setUserModel(CustomUser::class);
}
Token Blacklisting:
revokeToken() method in JwtUser to manually invalidate tokens:
public function revokeToken() {
$this->api_token = null;
$this->save();
}
Email Templates:
resources/views/vendor/jwt-auth/emails/. Key files:
registration.blade.phplogin.blade.phppassword_reset.blade.php (if using password reset).API Token Rotation:
JwtAuth::logout(); // Revokes current token
$newToken = JwtAuth::attempt($credentials); // Issues a new one
How can I help you explore Laravel packages today?