betterauth/laravel
Composer 安装命令:
composer require betterauth/laravel
包简介
Modern authentication for Laravel with Paseto V4 tokens, OAuth, 2FA, and Magic Links
README 文档
README
Modern authentication for Laravel with Paseto V4 tokens, 2FA, and Magic Links
Installation • Quick Start • Features • API Reference
Why BetterAuth?
| JWT | BetterAuth (Paseto V4) |
|---|---|
| Signed only | Encrypted + Authenticated |
| Algorithm confusion attacks | Single secure algorithm |
| Complex key management | Simple symmetric keys |
| Base64 encoded payload | Encrypted payload |
BetterAuth uses Paseto V4 (Platform-Agnostic Security Tokens) - a modern, secure alternative to JWT that eliminates entire classes of vulnerabilities by design.
Installation
composer require betterauth/laravel
php artisan betterauth:install
That's it. The installer configures everything automatically.
Quick Start
use BetterAuth\Laravel\Facades\BetterAuth; // Register $result = BetterAuth::signUp([ 'email' => 'user@example.com', 'password' => 'securepassword', ]); // Login $result = BetterAuth::signIn('user@example.com', 'password'); // → access_token, refresh_token, user // Verify token $payload = BetterAuth::verify($accessToken); // Protected routes Route::middleware('auth:betterauth')->get('/me', fn() => auth()->user());
Features
Core Authentication
- Paseto V4 Tokens - Encrypted, not just signed
- Argon2id Passwords - Memory-hard hashing (PHC winner)
- Refresh Token Rotation - One-time use with automatic rotation
- UUID v7 IDs - Time-ordered, database-friendly
Advanced Features
- Two-Factor Auth (TOTP) - With recovery codes
- Magic Links - Passwordless email authentication
- OAuth Providers - Google, GitHub, Facebook, and more
- Passkeys/WebAuthn - Biometric authentication (coming soon)
Laravel Native
- Works with
Auth::guard('betterauth') - Eloquent models and migrations
- Artisan commands
- Event dispatching
Requirements
| Requirement | Version |
|---|---|
| PHP | 8.2+ |
| Laravel | 10, 11, 12 |
| Database | PostgreSQL, MySQL, SQLite |
Configuration
After installation, configure via environment variables:
BETTERAUTH_SECRET=your-64-character-secret-key BETTERAUTH_MODE=api BETTERAUTH_ACCESS_LIFETIME=3600 BETTERAUTH_REFRESH_LIFETIME=2592000
Or edit config/betterauth.php:
return [ 'mode' => 'api', // 'api', 'session', 'hybrid' 'secret' => env('BETTERAUTH_SECRET'), 'tokens' => [ 'access_lifetime' => 3600, // 1 hour 'refresh_lifetime' => 2592000, // 30 days ], 'user_model' => App\Models\User::class, 'id_strategy' => 'uuid', // 'uuid' or 'int' ];
Generate a new secret key:
php artisan betterauth:secret
API Reference
Authentication Endpoints
| Method | Endpoint | Description |
|---|---|---|
POST |
/auth/register |
Create new account |
POST |
/auth/login |
Authenticate user |
GET |
/auth/me |
Get current user |
POST |
/auth/refresh |
Refresh access token |
POST |
/auth/logout |
Revoke refresh token |
POST |
/auth/revoke-all |
Revoke all tokens |
PUT |
/auth/password |
Update password |
Two-Factor Authentication
| Method | Endpoint | Description |
|---|---|---|
GET |
/auth/2fa/status |
Check 2FA status |
POST |
/auth/2fa/setup |
Get QR code |
POST |
/auth/2fa/enable |
Enable 2FA |
POST |
/auth/2fa/verify |
Verify TOTP code |
POST |
/auth/2fa/recovery |
Use recovery code |
DELETE |
/auth/2fa |
Disable 2FA |
Magic Links
| Method | Endpoint | Description |
|---|---|---|
POST |
/auth/magic-link |
Send magic link |
GET |
/auth/magic-link/verify |
Verify and login |
User Model
Add the HasBetterAuth trait to your User model:
use BetterAuth\Laravel\Models\Traits\HasBetterAuth; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use HasBetterAuth; protected $fillable = ['email', 'password', 'name']; }
The trait provides:
$user->getRoles(); // ['ROLE_USER', 'ROLE_ADMIN'] $user->hasRole('ROLE_ADMIN'); // true/false $user->addRole('ROLE_ADMIN'); $user->removeRole('ROLE_ADMIN'); $user->createTokens(); // Generate new token pair $user->revokeAllTokens(); // Revoke all refresh tokens
Two-Factor Authentication
Enable in configuration:
// config/betterauth.php 'two_factor' => [ 'enabled' => true, 'issuer' => 'My App', ],
Using the service:
use BetterAuth\Laravel\Services\TwoFactorService; $twoFactor = app(TwoFactorService::class); // Setup $setup = $twoFactor->generateSecret($user); // → secret, qr_code_url, uri // Enable $result = $twoFactor->verifyAndEnable($user, '123456'); // → enabled, recovery_codes // Verify $valid = $twoFactor->verify($user, '123456');
Magic Links
Enable in configuration:
// config/betterauth.php 'magic_link' => [ 'enabled' => true, 'expire' => 15, // minutes ],
Using the service:
use BetterAuth\Laravel\Services\MagicLinkService; $magicLink = app(MagicLinkService::class); $magicLink->send('user@example.com');
Events
| Event | Trigger |
|---|---|
UserRegistered |
New user signs up |
UserLoggedIn |
Successful authentication |
UserLoggedOut |
User signs out |
TokenRefreshed |
Refresh token used |
PasswordChanged |
Password updated |
TwoFactorEnabled |
2FA activated |
TwoFactorDisabled |
2FA deactivated |
MagicLinkSent |
Magic link email sent |
// EventServiceProvider.php protected $listen = [ \BetterAuth\Laravel\Events\UserRegistered::class => [ \App\Listeners\SendWelcomeEmail::class, ], ];
Middleware
// Require authentication Route::middleware('auth:betterauth')->group(function () { // Protected routes }); // Require email verification Route::middleware(['auth:betterauth', EnsureEmailIsVerified::class])->group(...); // Require 2FA enabled Route::middleware(['auth:betterauth', RequiresTwoFactor::class])->group(...);
Security
Token Security (Paseto V4)
- XChaCha20-Poly1305 encryption
- Tokens are encrypted, not just signed
- No algorithm confusion attacks
- No key type confusion
Password Security (Argon2id)
- Winner of Password Hashing Competition
- Memory-hard to prevent GPU attacks
- Configurable memory/time/threads
Refresh Token Security
- Hashed before storage (SHA-256)
- One-time use - revoked after refresh
- Automatic rotation - new token on each refresh
Testing
# Run tests composer test # With coverage composer test-coverage # Static analysis composer phpstan
License
MIT License. See LICENSE for details.
betterauth/laravel 适用场景与选型建议
betterauth/laravel 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 5 次下载、GitHub Stars 达 2, 最近一次更新时间为 2026 年 01 月 05 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「Authentication」 「oauth」 「laravel」 「2fa」 「paseto」 「magic-link」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 betterauth/laravel 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 betterauth/laravel 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 betterauth/laravel 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
WeChat OAuth SDK
Automatically logs-in users if they are already authenticated by a remote source. (e.g. environment variable REMOTE_USER)
GraphQL authentication for your headless Craft CMS applications.
Ory-Hydra OAuth 2.0 Client Provider for The PHP League OAuth2-Client
Library for ORCID web services
A lightweight and powerful OAuth 2.0 authorization and resource server library with support for all the core specification grants. This library will allow you to secure your API with OAuth and allow your applications users to approve apps that want to access their data from your API.
统计信息
- 总下载量: 5
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 2
- 点击次数: 30
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-01-05