承接 nadun24/laravel-hybrid-auth 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

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

nadun24/laravel-hybrid-auth

最新稳定版本:v1.0.2

Composer 安装命令:

composer require nadun24/laravel-hybrid-auth

包简介

Redis-first, database-fallback authentication system for Laravel with Sanctum-compatible API

README 文档

README

A high-performance Redis-first, database-fallback authentication system for Laravel with a Sanctum-compatible API. This package provides lightning-fast token validation using Redis while maintaining reliability through automatic database fallback when Redis is unavailable.

Features

  • 🚀 Redis-First Performance: Token validation in microseconds using Redis
  • 💾 Automatic DB Fallback: Seamless fallback to database when Redis is down
  • 🔄 Sanctum-Compatible API: Drop-in replacement for Laravel Sanctum
  • 🎯 Token Abilities: Fine-grained permissions for API tokens
  • Automatic Sync: Database tokens automatically sync to Redis
  • 🔒 Secure: SHA-256 hashed tokens with configurable expiration
  • 📊 Health Monitoring: Built-in Redis health checks with caching
  • 🎨 Zero Configuration: Works out of the box with sensible defaults

Requirements

  • PHP 8.1 or higher
  • Laravel 10.x or 11.x
  • Redis server (optional but recommended)
  • MySQL/PostgreSQL/SQLite

Installation

1. Install via Composer

composer require Nadun24/laravel-hybrid-auth

2. Publish Configuration and Migrations

php artisan vendor:publish --tag=hybrid-auth-config
php artisan vendor:publish --tag=hybrid-auth-migrations

3. Run Migrations

php artisan migrate

4. Configure Authentication Guard

In config/auth.php, add the hybrid-token guard:

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

    'api' => [
        'driver' => 'hybrid-token',
        'provider' => 'users',
    ],
],

5. Add Trait to User Model

Add the HasApiTokens trait to your User model:

use Nadun24\LaravelHybridAuth\Traits\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens;
    
    // ... rest of your model
}

Configuration

The configuration file is located at config/hybrid-auth.php:

return [
    // Redis connection settings
    'redis' => [
        'connection' => env('HYBRID_AUTH_REDIS_CONNECTION', 'default'),
        'prefix' => env('HYBRID_AUTH_REDIS_PREFIX', 'hybrid_auth'),
    ],

    // Database settings
    'database' => [
        'connection' => env('HYBRID_AUTH_DB_CONNECTION', null),
        'table' => 'personal_access_tokens',
    ],

    // Token expiration in minutes (null = never expires)
    'expiration' => env('HYBRID_AUTH_EXPIRATION', null),
    
    // Optional token prefix
    'token_prefix' => env('HYBRID_AUTH_TOKEN_PREFIX', ''),

    // Redis health check settings
    'redis_timeout' => env('HYBRID_AUTH_REDIS_TIMEOUT', 0.1),
    'redis_retry_after' => env('HYBRID_AUTH_REDIS_RETRY_AFTER', 60),
    'cache_redis_status' => env('HYBRID_AUTH_CACHE_REDIS_STATUS', true),

    // Enable/disable token abilities
    'abilities_enabled' => env('HYBRID_AUTH_ABILITIES_ENABLED', true),
];

Usage

Creating Tokens

Basic Token Creation

$user = User::find(1);

// Create a token with all abilities
$token = $user->createToken('mobile-app');

// Access the plain text token (only available once)
$plainTextToken = $token->plainTextToken;

// Return to user
return response()->json([
    'token' => $plainTextToken,
    'type' => 'Bearer'
]);

Token with Specific Abilities

$token = $user->createToken('admin-token', ['create', 'update', 'delete']);

Token with Expiration

$expiresAt = now()->addDays(30);
$token = $user->createToken('temp-token', ['*'], $expiresAt);

Authenticating Requests

Protect Routes

In routes/api.php:

use Illuminate\Support\Facades\Route;

Route::middleware('auth:api')->group(function () {
    Route::get('/user', function (Request $request) {
        return $request->user();
    });
    
    Route::post('/posts', [PostController::class, 'store']);
});

Making Authenticated Requests

Include the token in the Authorization header:

curl -H "Authorization: Bearer YOUR_TOKEN_HERE" \
     https://your-app.com/api/user

Or as a query parameter:

curl https://your-app.com/api/user?access_token=YOUR_TOKEN_HERE

Checking Token Abilities

In Controllers

public function store(Request $request)
{
    if ($request->user()->tokenCan('create')) {
        // User has 'create' ability
        return Post::create($request->all());
    }
    
    return response()->json(['message' => 'Forbidden'], 403);
}

Using Middleware

Register middleware in app/Http/Kernel.php:

protected $middlewareAliases = [
    // ... other middleware
    'abilities' => \Nadun24\LaravelHybridAuth\Middleware\CheckAbilities::class,
    'ability' => \Nadun24\LaravelHybridAuth\Middleware\CheckForAnyAbility::class,
];

Protect routes with required abilities:

// User must have ALL specified abilities
Route::post('/admin/users', [UserController::class, 'store'])
    ->middleware(['auth:api', 'abilities:create,update']);

// User must have ANY of the specified abilities
Route::get('/reports', [ReportController::class, 'index'])
    ->middleware(['auth:api', 'ability:view-reports,view-analytics']);

Managing Tokens

Get User's Tokens

$tokens = $user->tokens;

foreach ($tokens as $token) {
    echo $token->name;
    echo $token->last_used_at;
}

Revoke Current Token

// In a controller
public function logout(Request $request)
{
    $request->user()->revokeCurrentToken();
    
    return response()->json(['message' => 'Logged out successfully']);
}

Revoke All Tokens

$user->revokeAllTokens();

Delete Specific Token

$user->tokens()->where('name', 'mobile-app')->delete();

How It Works

Token Creation Flow

  1. Plain text token is generated
  2. Token is hashed using SHA-256
  3. Token is stored in Redis (if available)
  4. Token is stored in database (always)
  5. Plain text token is returned to user (only once)

Token Validation Flow

  1. Request arrives with token
  2. Token is hashed
  3. Redis Check: Hash is looked up in Redis (microsecond latency)
    • If found: User is authenticated immediately
    • If not found or Redis down: Continue to step 4
  4. Database Fallback: Hash is looked up in database
    • If found: User is authenticated and token is synced to Redis
    • If not found: Authentication fails

Redis Health Monitoring

  • Automatic Redis connection health checks
  • Failed connections are cached to prevent repeated failures
  • Configurable retry intervals
  • Transparent fallback to database

Performance Benefits

With Redis Available

  • Token Validation: < 1ms (vs 10-50ms database query)
  • Concurrent Requests: Handles 10,000+ req/sec per server
  • Database Load: Reduced by 90%+

With Redis Down

  • Automatic Fallback: Zero downtime
  • Transparent Operation: No code changes needed
  • Database Validation: Standard Laravel performance

Testing

Run the test suite:

composer test

Run with coverage:

composer test:coverage

Best Practices

1. Token Security

// ✅ Good: Store tokens securely on client
localStorage.setItem('api_token', token);

// ❌ Bad: Never expose tokens in URLs permanently
https://app.com/dashboard?token=xyz  // Avoid this

2. Token Abilities

// ✅ Good: Use specific abilities
$token = $user->createToken('mobile', ['read', 'write']);

// ❌ Bad: Don't give all abilities unless necessary
$token = $user->createToken('mobile', ['*']);  // Use sparingly

3. Token Expiration

// ✅ Good: Set expiration for sensitive operations
$token = $user->createToken('payment', ['payment'], now()->addHours(1));

// ✅ Good: Long-lived tokens for mobile apps
$token = $user->createToken('mobile', ['*'], now()->addYear());

4. Redis Configuration

# Recommended production settings
HYBRID_AUTH_REDIS_CONNECTION=cache
HYBRID_AUTH_REDIS_PREFIX=auth
HYBRID_AUTH_REDIS_TIMEOUT=0.1
HYBRID_AUTH_REDIS_RETRY_AFTER=60
HYBRID_AUTH_CACHE_REDIS_STATUS=true

Troubleshooting

Redis Connection Issues

If you see warnings about Redis connections:

  1. Check Redis is running: redis-cli ping
  2. Verify connection settings in .env
  3. Check firewall rules
  4. Review config/database.php Redis configuration

The package will automatically fall back to database validation.

Token Not Working

  1. Ensure token is sent in correct format: Bearer TOKEN
  2. Check token hasn't expired
  3. Verify guard is set to api in routes
  4. Check user model has HasApiTokens trait

Performance Issues

  1. Enable Redis for best performance
  2. Set appropriate redis_retry_after value
  3. Enable cache_redis_status to reduce connection checks
  4. Add database indexes on personal_access_tokens.token

Migration from Sanctum

This package is designed as a drop-in replacement for Laravel Sanctum:

  1. Install this package
  2. Replace Laravel\Sanctum\HasApiTokens with Nadun24\LaravelHybridAuth\Traits\HasApiTokens
  3. Update guard from sanctum to hybrid-token in config/auth.php
  4. Update middleware from auth:sanctum to auth:api

Your existing token creation and validation code should work without changes!

Contributing

Contributions are welcome! Please submit pull requests or issues on GitHub.

License

This package is open-sourced software licensed under the MIT license.

Credits

Inspired by Laravel Sanctum and built to provide enhanced performance through Redis caching while maintaining reliability.

Support

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

统计信息

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

GitHub 信息

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

其他信息

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