listradigital/laravel-auth-api-sanctum
Composer 安装命令:
composer require listradigital/laravel-auth-api-sanctum
包简介
SPA-ready authentication API for Laravel with Sanctum (register, login, logout, email verification, password reset)
README 文档
README
SPA-ready authentication API for Laravel with Sanctum. Provides register, login, logout, email verification, password reset, and a protected /me endpoint—all configurable and using httpOnly cookies for security.
Installation
composer require tilistra/laravel-auth-api-sanctum
Publish the config file:
php artisan vendor:publish --tag="laravel-auth-api-sanctum-config"
Publish pt-BR translations (validation and passwords) for 422 error messages:
php artisan vendor:publish --tag=lang
Then set config('app.locale') to pt_BR in your application.
Publish package documentation into your app under docs/packages/{vendor}/{package}/{installed-version}/:
php artisan vendor:publish --tag=laravel-auth-api-sanctum-docs
Publish and run Sanctum migrations:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
User Model Setup
Your User model must implement MustVerifyEmail and use HasApiTokens, Notifiable. Override the notification methods to use the package's queued notifications:
use AuthApiSanctum\Concerns\HasAuthApiSanctumNotifications;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable implements MustVerifyEmail
{
use HasApiTokens, HasAuthApiSanctumNotifications, HasFactory, Notifiable;
// ...
}
Or manually override:
public function sendEmailVerificationNotification(): void
{
$this->notify(new \AuthApiSanctum\Notifications\VerifyEmailQueued);
}
public function sendPasswordResetNotification($token): void
{
$this->notify(new \AuthApiSanctum\Notifications\ResetPasswordQueued($token));
}
Bootstrap Configuration (Laravel 11+)
In bootstrap/app.php, ensure stateful API and throttle are enabled:
->withMiddleware(function (Middleware $middleware): void {
$middleware->statefulApi();
$middleware->throttleApi();
$middleware->alias([
'verified.email' => \AuthApiSanctum\Http\Middleware\EnsureEmailIsVerifiedConfigurable::class,
]);
})
Exception Handlers (401, 403, 404, 500)
To return empty body for 401, 403, 404, 500 etc. on auth API routes (RF-4, RF-5), configure your application's exception handler. Use AuthApiSanctum::isAuthApiRequest() to detect requests targeting this package's routes:
// In bootstrap/app.php (Laravel 11+) or App\Exceptions\Handler
use AuthApiSanctum\AuthApiSanctum;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Request;
use Illuminate\Foundation\Configuration\Exceptions;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->render(function (AuthenticationException $e, Request $request) {
if (AuthApiSanctum::isAuthApiRequest($request)) {
return response('', 401);
}
});
$exceptions->render(function (AccessDeniedHttpException $e, Request $request) {
if (AuthApiSanctum::isAuthApiRequest($request)) {
return response('', 403);
}
});
$exceptions->render(function (NotFoundHttpException $e, Request $request) {
if (AuthApiSanctum::isAuthApiRequest($request)) {
return response('', 404);
}
});
// For 500 and other HTTP errors, check if exception has getStatusCode()
$exceptions->render(function (Throwable $e, Request $request) {
if (! AuthApiSanctum::isAuthApiRequest($request)) {
return null;
}
$status = method_exists($e, 'getStatusCode') ? $e->getStatusCode() : 500;
return response('', $status);
});
})
For Laravel 10 or custom Handler, use the renderable method with the same logic. The package already customizes 422 (validation) to return {"errors": {...}} without message.
Auth Config Integration
In config/auth.php, use the package values for password reset and email verification expiry:
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_reset_tokens',
'expire' => config('auth_api_sanctum.password_reset_token_expiration_minutes', 60),
'throttle' => 60,
],
],
'verification' => [
'expire' => config('auth_api_sanctum.email_verification_expire_minutes', 60),
],
CORS
Ensure config/cors.php allows credentials for your SPA origin:
'supports_credentials' => true,
'allowed_origins' => [env('FRONTEND_URL', 'http://localhost:3000')],
Configuration
Published config (config/auth_api_sanctum.php):
| Key | Env | Default | Description |
|---|---|---|---|
require_email_verification | AUTH_REQUIRE_EMAIL_VERIFICATION | true | Block protected routes until email verified |
remember_me_expiration_days | AUTH_REMEMBER_ME_EXPIRATION_DAYS | 5 | Session duration when "remember me" checked |
password_reset_token_expiration_minutes | AUTH_PASSWORD_RESET_EXPIRATION_MINUTES | 60 | Password reset link validity |
email_verification_expire_minutes | AUTH_EMAIL_VERIFICATION_EXPIRE_MINUTES | 60 | Verification link validity |
frontend_reset_password_url | FRONTEND_RESET_PASSWORD_URL | APP_URL | Base URL for reset link |
route_prefix | AUTH_API_SANCTUM_ROUTE_PREFIX | '' | Prefix for auth routes |
api_rate_limit | AUTH_API_RATE_LIMIT | 60 | Requests per minute for API |
API Endpoints
| Method | Route | Auth | Description |
|---|---|---|---|
| POST | /sanctum/csrf-cookie | No | Get CSRF cookie (call before login) |
| POST | /register | No | Create user, optional verification email |
| POST | /login | No | Authenticate, returns user |
| POST | /logout | Yes | Invalidate session |
| GET | /me | Yes | Current user (requires verified email if enabled) |
| POST | /forgot-password | No | Send reset email |
| POST | /reset-password | No | Reset password with token |
| GET | /email/verify/{id}/{hash} | No | Verify email via signed link |
Testing
composer test
Changelog
See CHANGELOG for recent changes.
License
MIT. See LICENSE.
listradigital/laravel-auth-api-sanctum 适用场景与选型建议
listradigital/laravel-auth-api-sanctum 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 03 月 18 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「Authentication」 「laravel」 「SPA」 「sanctum」 「auth-api-sanctum」 「laravel-auth-api-sanctum」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 listradigital/laravel-auth-api-sanctum 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 listradigital/laravel-auth-api-sanctum 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 listradigital/laravel-auth-api-sanctum 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
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.
A Laravel-Nuxt starter project template.
Laravel middleware to restrict a site or specific routes using HTTP basic authentication
Email Toolkit Plugin for CakePHP
Appui DOM Interface
统计信息
- 总下载量: 1
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 34
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-03-18