nadun24/laravel-hybrid-auth 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

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

nadun24/laravel-hybrid-auth

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.

nadun24/laravel-hybrid-auth 适用场景与选型建议

nadun24/laravel-hybrid-auth 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 2 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 12 月 13 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「redis」 「api」 「Authentication」 「laravel」 「token」 「sanctum」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 nadun24/laravel-hybrid-auth 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 nadun24/laravel-hybrid-auth 我们能提供哪些服务?
定制开发 / 二次开发

基于 nadun24/laravel-hybrid-auth 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

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

GitHub 信息

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

其他信息

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