betterauth/core
最新稳定版本:v3.0.1
Composer 安装命令:
composer require betterauth/core
包简介
Framework-agnostic authentication library for PHP - Core package
README 文档
README
Framework-agnostic authentication library for PHP 8.2+.
✨ Features
- ???? Multiple authentication methods: Email/Password, Magic Link, OAuth, TOTP
- ???? OAuth Providers: Google, GitHub, Facebook, Microsoft, Discord
- ???? Multi-tenant capabilities: Organizations, Teams, Members, Invitations with RBAC
- ???? Secure by default: Paseto V4 tokens, Argon2id hashing
- ???? Multiple storage adapters: PDO, Doctrine
- ???? Framework-agnostic core: Use with any PHP framework
- ???? UUID v7 support: Time-ordered, non-guessable IDs
- ???? Plugin system: Extensible architecture
- ???? Security audit trail: Events logging & monitoring
???? Installation
composer require betterauth/core
???? Framework Integrations
BetterAuth Core is framework-agnostic with official integrations:
- Symfony (✅ Production Ready):
betterauth/symfony-bundle - Vanilla PHP: Use this package directly with PDO storage adapters
???? Requirements
- PHP 8.2 or higher
- ext-json
- ext-openssl
- ramsey/uuid ^4.7
- paragonie/paseto ^3.1
???? Quick Start (Vanilla PHP with PDO)
<?php use BetterAuth\Core\Config\AuthConfig; use BetterAuth\Core\PasswordHasher; use BetterAuth\Core\TokenAuthManager; use BetterAuth\Core\TokenService; use BetterAuth\Storage\Pdo\PdoRefreshTokenRepository; use BetterAuth\Storage\Pdo\PdoUserRepository; // Database setup $pdo = new PDO('sqlite:database.db'); // Create repositories $userRepo = new PdoUserRepository($pdo); $refreshTokenRepo = new PdoRefreshTokenRepository($pdo); // Configure authentication (API mode with Paseto) $config = AuthConfig::forApi( secretKey: 'your-256-bit-secret-key', // 32+ chars overrides: [ 'tokenLifetime' => 3600, // Access token: 1h 'refreshTokenLifetime' => 2592000, // Refresh token: 30d ] ); // Crypto/services $tokenSigner = new TokenService($config->secretKey); $passwordHasher = new PasswordHasher(); // Create auth manager (stateless API tokens) $auth = new TokenAuthManager( userRepository: $userRepo, refreshTokenRepository: $refreshTokenRepo, tokenService: $tokenSigner, passwordHasher: $passwordHasher, config: $config, ); // Sign in (user must be created via SessionAuthManager or directly via repository) $result = $auth->signIn( email: 'user@example.com', password: 'SecurePassword123' ); // Access tokens $accessToken = $result['access_token']; $refreshToken = $result['refresh_token']; // Verify token and get user $payload = $auth->verify($accessToken);
???? Storage Adapters
PDO (Vanilla PHP)
use BetterAuth\Storage\Pdo\PdoUserRepository; use BetterAuth\Storage\Pdo\PdoSessionRepository; $pdo = new PDO('mysql:host=localhost;dbname=auth', 'user', 'password'); $userRepo = new PdoUserRepository($pdo); $sessionRepo = new PdoSessionRepository($pdo);
Doctrine (Symfony)
Use the betterauth/symfony-bundle which provides Doctrine integration.
???? Authentication Providers
Email/Password
use BetterAuth\Core\SessionAuthManager; // For registration, use SessionAuthManager $sessionAuth = new SessionAuthManager($config, $userRepo, $sessionRepo); $result = $sessionAuth->signUp( email: 'user@example.com', password: 'SecurePassword123', username: 'John Doe', ipAddress: $_SERVER['REMOTE_ADDR'], userAgent: $_SERVER['HTTP_USER_AGENT'] ); // For API authentication, use TokenAuthManager $tokenAuth = new TokenAuthManager($config, $userRepo, $refreshTokenRepo); $result = $tokenAuth->signIn( email: 'user@example.com', password: 'SecurePassword123' ); // Returns: ['user' => User, 'access_token' => '...', 'refresh_token' => '...', 'expires_in' => 3600]
OAuth 2.0
Note: Only Google OAuth is fully tested and production-ready (
[STABLE]). Other providers (GitHub, Facebook, Microsoft, Discord) are in[DRAFT]status.
use BetterAuth\Providers\OAuthProvider\OAuthManager; $oauthConfig = [ 'google' => [ 'clientId' => 'your-google-client-id', 'clientSecret' => 'your-google-client-secret', 'redirectUri' => 'https://yourapp.com/auth/google/callback', ], ]; $oauth = new OAuthManager($oauthConfig, $userRepo); // Redirect to OAuth provider $authUrl = $oauth->getAuthorizationUrl('google'); header("Location: $authUrl"); // Handle callback - creates or updates user automatically $result = $oauth->handleCallback('google', $_GET['code']); // Returns: ['user' => User, 'isNewUser' => bool, 'providerUser' => ProviderUser]
Magic Link
use BetterAuth\Providers\MagicLinkProvider\MagicLinkProvider; $magicLink = new MagicLinkProvider($config, $userRepo, $magicLinkStorage, $emailSender); // Create magic link token $token = $magicLink->createToken('user@example.com'); // Token is automatically sent via configured EmailSender // Verify magic link and authenticate user $result = $magicLink->verify($token); // Returns: ['user' => User, 'session' => Session] or tokens depending on mode
TOTP (Two-Factor Authentication)
use BetterAuth\Providers\TotpProvider\TotpProvider; $totp = new TotpProvider($config, $totpStorage); // Generate secret and QR code for user $result = $totp->generateSecret($userId, 'user@example.com'); // Returns: [ // 'secret' => 'JBSWY3DPEHPK3PXP', // 'qrCode' => 'data:image/png;base64,...', // 'qrCodeUrl' => 'otpauth://totp/...' // ] // Enable TOTP after user confirms with first code $totp->enable($userId, $result['secret'], '123456'); // Verify TOTP code during login $isValid = $totp->verify($userId, '123456');
???? Security Features
Token Management
BetterAuth uses Paseto V4 tokens (encrypted, authenticated):
// Access token (short-lived) $accessToken = $result['access_token']; // Valid for 1 hour (default) // Refresh token (long-lived) $refreshToken = $result['refresh_token']; // Valid for 30 days // Refresh access token $newResult = $auth->refresh($refreshToken); // Returns new access_token and optionally rotated refresh_token
Password Hashing
Passwords are hashed using Argon2id (memory-hard, resistant to GPU attacks):
// Automatic during signUp $result = $sessionAuth->signUp( email: 'user@example.com', password: 'SecurePassword123', // Hashed with Argon2id ipAddress: $_SERVER['REMOTE_ADDR'], userAgent: $_SERVER['HTTP_USER_AGENT'] );
UUID v7 IDs
BetterAuth supports time-ordered UUIDs for better database performance:
// Example UUID v7 (time-ordered, non-guessable) $user->id; // "019ab13e-40f1-7b21-a672-f403d5277ec7" // Benefits: // - Chronologically sortable // - Non-guessable (secure) // - No index fragmentation (fast DB queries)
⚙️ Configuration
use BetterAuth\Core\Config\AuthConfig; $config = new AuthConfig( secret: 'your-256-bit-secret-key', tokenLifetime: 3600, // Access token: 1 hour (default) refreshLifetime: 2592000, // Refresh token: 30 days passwordMinLength: 8, requireEmailVerification: true, enableDeviceTrust: true, enableSecurityNotifications: true );
Rate Limiting
BetterAuth includes built-in rate limiting protection (enabled by default):
- Max attempts: 5 per IP/email combination
- Decay time: 300 seconds (5 minutes)
// Rate limiting is automatically enforced on signIn attempts // After 5 failed attempts, the user must wait 5 minutes
???? Multi-Tenancy
use BetterAuth\Providers\AccountLinkProvider\OrganizationManager; $orgManager = new OrganizationManager($userRepo); // Create organization $org = $orgManager->createOrganization( name: 'Acme Inc', ownerId: $userId ); // Invite members $orgManager->inviteMember( organizationId: $org->id, email: 'member@example.com', role: 'admin' ); // Accept invitation $orgManager->acceptInvitation($token);
???? Testing
# Run PHPUnit tests composer test # Run PHPStan static analysis composer phpstan # Run Behat BDD scenarios vendor/bin/behat # Run code style fixer composer cs-fix
???? CI/CD
BetterAuth Core includes comprehensive CI/CD with GitHub Actions:
- ✅ PHPUnit tests (PHP 8.2, 8.3, 8.4)
- ✅ PHPStan static analysis (level 5)
- ✅ Security checks (Composer audit + Symfony security checker)
- ✅ Behat BDD scenarios
- ✅ Code quality checks (PHP CS Fixer)
All tests run on every push and pull request. View the latest CI results.
???? Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
???? Security
If you discover any security-related issues, please create an issue on GitHub with the security label.
???? License
The MIT License (MIT). Please see LICENSE file for details.
???? Links
- Packagist: https://packagist.org/packages/betterauth/core
- GitHub: https://github.com/MakFly/betterauth-core
- Issues: https://github.com/MakFly/betterauth-core/issues
- Symfony Bundle: https://github.com/MakFly/betterauth-symfony
???? Credits
- BackToTheFutur Team
- All the amazing people who contribute to open source
Made with ❤️ by the BackToTheFutur Team
betterauth/core 适用场景与选型建议
betterauth/core 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 813 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 01 月 04 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「Authentication」 「oauth」 「SSO」 「auth」 「totp」 「multi-tenant」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 betterauth/core 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 betterauth/core 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 betterauth/core 相关的其它包
同方向 / 同关键字的高下载量 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.
统计信息
- 总下载量: 813
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 37
- 依赖项目数: 1
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-01-04