martin6363/laravel-api-auth

Professional, configuration-driven API authentication package for Laravel 12+ using Sanctum

Maintainers

Package info

github.com/Martin6363/laravel-api-auth

pkg:composer/martin6363/laravel-api-auth

Statistics

Installs: 3

Dependents: 0

Suggesters: 0

Stars: 1

Open Issues: 0

v1.4.1 2026-02-12 10:04 UTC

This package is auto-updated.

Last update: 2026-03-12 10:24:15 UTC


README

Latest Version on Packagist Total Downloads Software License License

A professional, configuration-driven API authentication package for Laravel 11 & 12+ using Laravel Sanctum. Built with clean architecture principles and designed for easy customization.

โœจ Features

  • ๐Ÿ” 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

๐Ÿ“‹ Requirements

  • PHP >= 8.2+
  • Laravel >= 11.0 or >= 12.0
  • Laravel Sanctum >= 4.0

๐Ÿš€ Installation

Step 1: Install via Composer

composer require martin6363/laravel-api-auth

Step 2: Install Laravel Sanctum (if not already installed)

composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate

Step 3: Install the Package

php artisan api-auth:install  # --force will update the existing config file

This command will:

  • Publish the configuration file to config/api-auth.php
  • Check for Laravel Sanctum installation
  • Optionally run migrations

๐Ÿ—‘๏ธ > Uninstallation

If you need to remove the package and all its published components (config, controllers, services, etc.), run:

php artisan api-auth:uninstall

Step 4 (Optional): Publish Logics (Controllers, Services)

  • 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-logic

Step 5: Configure Your User Model

Ensure your User model uses the HasApiTokens trait from Laravel Sanctum:

use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
    // ...
}

Step 6: Configure Email (Optional)

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}"

โš™๏ธ Configuration

After installation, you can customize the package behavior by editing config/api-auth.php:

User Model

'user_model' => \App\Models\User::class,

Token Configuration

'token' => [
    'name' => 'auth_token',           // Token name
    'abilities' => ['*'],             // Token abilities
    'expires_at' => null,            // Token expiration (null = no expiration)
],

Route Configuration

'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

'email_verification' => [
    'required' => false,              // Require verification on registration
    'send_on_register' => true,       // Auto-send verification email
],

Email Theme Customization

  • 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 Configuration

'password' => [
    'min_length' => 8,                // Minimum password length
    'require_confirmation' => true,    // Require password confirmation
    'reset_token_expires' => 60,       // Reset token expiration (minutes)
],

Rate Limiting

'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
],

๐Ÿ“ก API Endpoints

Public Endpoints

Register

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"
        }
    }
}

Login

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"
        }
    }
}

Login Configuration (Dynamic Identification)

  • 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',], 
],

Forgot Password

POST /api/auth/forgot-password
Content-Type: application/json

{
    "email": "john@example.com"
}

Reset Password

POST /api/auth/reset-password
Content-Type: application/json

{
    "token": "reset_token_here",
    "email": "john@example.com",
    "password": "newpassword123",
    "password_confirmation": "newpassword123"
}

Protected Endpoints (Require Authentication)

All protected endpoints require the Authorization header:

Authorization: Bearer {token}

Get Profile

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"
        }
    }
}

Refresh Token

POST /api/auth/refresh-token
Authorization: Bearer {token}

Response:

{
    "message": "Token refreshed successfully",
    "data": {
        "token": "2|xxxxxxxxxxxx",
        "token_type": "Bearer",
        "user": {  }
    }
}

Logout

POST /api/auth/logout
Authorization: Bearer {token}

Response:

{
    "message": "Logged out successfully"
}

Send Email Verification

POST /api/auth/email/verification-notification
Authorization: Bearer {token}

Verify Email

GET /api/auth/email/verify/{id}/{hash}

๐Ÿ”ง Customization

Adding Custom Fields to Registration

You can easily add custom fields to the registration process by adding them to the validation configuration. The package will automatically:

  1. Validate the fields during registration
  2. Save them to the database
  3. Include them in API responses

Example: Adding a phone number field

  1. 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'],
],
  1. Make sure your User model's $fillable array includes the new field:
protected $fillable = [
    'name',
    'email',
    'password',
    'phone',      // Add your custom field
    'username',   // Add your custom field
];
  1. 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"
}

Customizing Validation Rules

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 email field automatically gets a unique rule for registration
  • The password field automatically gets min_length and confirmed rules based on config
  • All other fields use the rules you specify exactly as configured

Extending Services

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();
});

Customizing Routes

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
],

๐Ÿ›ก๏ธ Security Features

  • 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

๐Ÿงช Testing

The package includes test examples. Run tests with:

php artisan test

Or with Pest:

./vendor/bin/pest

Publish Logic

  • [!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 Notifications

๐Ÿ“ License

This package is open-sourced software licensed under the MIT license.

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

๐Ÿ“ง Support

For issues, questions, or contributions, please open an issue on the GitHub repository.

๐Ÿ™ Credits

Built with โค๏ธ for the Laravel community.