定制 devkit2026/laravel-jwt-auth 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

devkit2026/laravel-jwt-auth

最新稳定版本:v0.0.5

Composer 安装命令:

composer require devkit2026/laravel-jwt-auth

包简介

A standalone JWT authentication module for Laravel.

README 文档

README

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

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

1. Install via Composer

composer require devkit2026/laravel-jwt-auth

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

php artisan migrate

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

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

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

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

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

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

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

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

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

GET /api/auth/me

Headers:

Authorization: Bearer {access_token}

Response (200):

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

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

The package returns standardized error responses:

Code HTTP Status Description
ERR_VALIDATION 422 Validation error
ERR_INVALID_CREDENTIALS 401 Invalid email or password
ERR_EMAIL_NOT_VERIFIED 403 Email not verified
ERR_ACCESS_TOKEN_EXPIRED 401 Access token expired
ERR_REFRESH_TOKEN_EXPIRED 401 Refresh token expired
ERR_REFRESH_TOKEN_REVOKED 401 Refresh token revoked
ERR_TOKEN_INVALID 401 Invalid token
ERR_TOKEN_MISSING 401 Token not provided
ERR_USER_NOT_FOUND 404 User not found

Error Response Format:

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

Testing

The package includes comprehensive tests. To run them:

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

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

The package dispatches the following events:

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

Customization

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

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

MIT

Support

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

统计信息

  • 总下载量: 5
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-12-02