A professional, configuration-driven API authentication package for Laravel 11 & 12+ using Laravel Sanctum. Built with clean architecture principles and designed for easy customization.
- π Complete Authentication Flow: Registration, Login, Logout
- π Dynamic Identification: Login using email, username, or any custom field
- π Token Management: Access tokens with refresh capability
- π Password Management: Forgot password and reset password functionality
- βοΈ Email Verification: Built-in email verification support (Queueable & Customizable)
- π€ User Profile: Get authenticated user profile endpoint
- π‘οΈ Rate Limiting: Configurable rate limiting for security
- βοΈ Highly Configurable: Extensive configuration options
- ποΈ Clean Architecture: Service-oriented design for easy extension
- π§ͺ Test Ready: Built with testing in mind
- PHP >= 8.2+
- Laravel >= 11.0 or >= 12.0
- Laravel Sanctum >= 4.0
composer require martin6363/laravel-api-authcomposer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migratephp artisan api-auth:install # --force will update the existing config fileThis command will:
- Publish the configuration file to
config/api-auth.php - Check for Laravel Sanctum installation
- Optionally run migrations
If you need to remove the package and all its published components (config, controllers, services, etc.), run:
php artisan api-auth:uninstall- If you want to customize the internal logic of the authentication (e.g., change the registration logic or add custom responses), you can publish the controllers, services to your application:
php artisan vendor:publish --tag=api-auth-logicEnsure your User model uses the HasApiTokens trait from Laravel Sanctum:
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
// ...
}If you're using email verification or password reset, configure your email settings in .env:
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your_username
MAIL_PASSWORD=your_password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=noreply@example.com
MAIL_FROM_NAME="${APP_NAME}"After installation, you can customize the package behavior by editing config/api-auth.php:
'user_model' => \App\Models\User::class,'token' => [
'name' => 'auth_token', // Token name
'abilities' => ['*'], // Token abilities
'expires_at' => null, // Token expiration (null = no expiration)
],'routes' => [
'prefix' => 'api/auth', // Route prefix
'middleware' => ['api'], // Route middleware
'enabled' => [
'register' => true,
'login' => true,
'logout' => true,
'forgot_password' => true,
'reset_password' => true,
'email_verification' => true,
'profile' => true,
'refresh_token' => true,
],
],'email_verification' => [
'required' => false, // Require verification on registration
'send_on_register' => true, // Auto-send verification email
],- Customize the look and feel of your verification emails directly from the config.
'emails' => [
'dispatch_mode' => 'queue', // 'queue' or 'sync'
'theme' => [
'primary_color' => '#4f46e5',
'button_text_color' => '#ffffff',
],
],'password' => [
'min_length' => 8, // Minimum password length
'require_confirmation' => true, // Require password confirmation
'reset_token_expires' => 60, // Reset token expiration (minutes)
],'rate_limiting' => [
'enabled' => true, // Enable rate limiting
'max_attempts' => 5, // Max attempts per minute (login/register)
'password_reset_max_attempts' => 3, // Max attempts for password reset
],POST /api/auth/register
Content-Type: application/json
{
"name": "John Doe",
"email": "john@example.com",
"password": "password123",
"password_confirmation": "password123"
}Response:
{
"message": "User registered successfully",
"data": {
"token": "1|xxxxxxxxxxxx",
"token_type": "Bearer",
"user": {
"id": 1,
"name": "John Doe",
"email": "john@example.com",
"created_at": "2024-01-01T00:00:00.000000Z"
}
}
}POST /api/auth/login
Content-Type: application/json
{
"login": "john@example.com", // Can be email or username ...
"password": "password123"
}Response:
{
"message": "Login successful",
"data": {
"token": "1|xxxxxxxxxxxx",
"token_type": "Bearer",
"user": {
"id": 1,
"name": "John Doe",
"email": "john@example.com"
}
}
}- You can allow users to log in using different fields (e.g., either email or username).
'login' => [
'fields' => [
'login' => ['required', 'string'], // The input field name from frontend
'password' => ['required', 'string'],
],
// The database columns to search for the user
'search_columns' => ['email',],
],POST /api/auth/forgot-password
Content-Type: application/json
{
"email": "john@example.com"
}POST /api/auth/reset-password
Content-Type: application/json
{
"token": "reset_token_here",
"email": "john@example.com",
"password": "newpassword123",
"password_confirmation": "newpassword123"
}All protected endpoints require the Authorization header:
Authorization: Bearer {token}GET /api/auth/profile
Authorization: Bearer {token}Response:
{
"message": "Profile retrieved successfully",
"data": {
"user": {
"id": 1,
"name": "John Doe",
"email": "john@example.com",
"email_verified_at": "2024-01-01T00:00:00.000000Z"
}
}
}POST /api/auth/refresh-token
Authorization: Bearer {token}Response:
{
"message": "Token refreshed successfully",
"data": {
"token": "2|xxxxxxxxxxxx",
"token_type": "Bearer",
"user": { }
}
}POST /api/auth/logout
Authorization: Bearer {token}Response:
{
"message": "Logged out successfully"
}POST /api/auth/email/verification-notification
Authorization: Bearer {token}GET /api/auth/email/verify/{id}/{hash}You can easily add custom fields to the registration process by adding them to the validation configuration. The package will automatically:
- Validate the fields during registration
- Save them to the database
- Include them in API responses
Example: Adding a phone number field
- Update your
config/api-auth.php:
'validation' => [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255'],
'password' => ['required', 'string'],
'phone' => ['nullable', 'string', 'max:20'], // Add your custom field
'username' => ['required', 'string', 'max:255', 'unique:users,username'],
],- Make sure your User model's
$fillablearray includes the new field:
protected $fillable = [
'name',
'email',
'password',
'phone', // Add your custom field
'username', // Add your custom field
];- The field will now be automatically:
- Validated during registration
- Saved to the database
- Included in API responses
Example Registration Request:
{
"name": "John Doe",
"email": "john@example.com",
"password": "password123",
"password_confirmation": "password123",
"phone": "+1234567890",
"username": "johndoe"
}Edit config/api-auth.php:
'validation' => [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255'],
'password' => ['required', 'string', 'min:12'], // Customize password rules
],Note:
- The
emailfield automatically gets auniquerule for registration - The
passwordfield automatically getsmin_lengthandconfirmedrules based on config - All other fields use the rules you specify exactly as configured
You can extend the services by binding your own implementations in a service provider:
use Martin6363\ApiAuth\Services\v1\AuthService;
$this->app->bind(AuthService::class, function ($app) {
return new CustomAuthService();
});You can disable specific routes in the configuration:
'routes' => [
'enabled' => [
'register' => false, // Disable registration
'login' => true,
// ...
],
],Or modify the route prefix:
'routes' => [
'prefix' => 'api/v1/auth', // Custom prefix
],- Rate Limiting: Prevents brute force attacks
- Password Hashing: Uses Laravel's secure password hashing
- Token Revocation: Tokens are revoked on password reset
- Email Verification: Optional email verification for new users
- CSRF Protection: Built-in CSRF protection for web routes
The package includes test examples. Run tests with:
php artisan testOr with Pest:
./vendor/bin/pest- [!IMPORTANT] Most of the package's behavior is controlled via the config/api-auth.php file. You should only publish and modify these files if you need to implement custom logic that cannot be achieved through configuration.
php artisan vendor:publish --tag=api-auth-logic ## Published controllers, services, and other logic files to your app for customization.php artisan vendor:publish --tag=api-auth-config # Configuration file
php artisan vendor:publish --tag=api-auth-lang # Language/Translation files
php artisan vendor:publish --tag=api-auth-controllers # Authentication Controllers
php artisan vendor:publish --tag=api-auth-services # Business logic services
php artisan vendor:publish --tag=api-auth-requests # Validation/Form Requests
php artisan vendor:publish --tag=api-auth-resources # API User Resources
php artisan vendor:publish --tag=api-auth-notifications # Email & System NotificationsThis package is open-sourced software licensed under the MIT license.
Contributions are welcome! Please feel free to submit a Pull Request.
For issues, questions, or contributions, please open an issue on the GitHub repository.
Built with β€οΈ for the Laravel community.