PHPackages                             hadefication/simple-token-auth - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. hadefication/simple-token-auth

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

hadefication/simple-token-auth
==============================

A lightweight Laravel package for server-to-server API authentication using static bearer tokens. This package provides a simpler alternative to Laravel Sanctum for internal APIs, microservices, and trusted system integrations. Uses spatie/laravel-package-tools package as base.

v1.0.0(9mo ago)12[4 PRs](https://github.com/hadefication/simple-token-auth/pulls)MITPHPPHP ^8.3CI passing

Since Aug 7Pushed 1mo agoCompare

[ Source](https://github.com/hadefication/simple-token-auth)[ Packagist](https://packagist.org/packages/hadefication/simple-token-auth)[ Docs](https://github.com/hadefication/simple-token-auth)[ GitHub Sponsors](https://github.com/:vendor_name)[ RSS](/packages/hadefication-simple-token-auth/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (13)Versions (6)Used By (0)

Simple Token Auth
=================

[](#simple-token-auth)

A lightweight, secure, and easy-to-use authentication package for server-to-server communication in Laravel applications. This package provides simple token-based authentication with built-in security features like rate limiting, timing attack protection, and comprehensive logging.

Features
--------

[](#features)

- 🔐 **Secure Token Validation**: Uses `hash_equals()` to prevent timing attacks
- 🚀 **Multiple Service Support**: Named tokens for different services with fallback support
- 🛡️ **Rate Limiting**: Built-in protection against brute-force attacks
- 📝 **Comprehensive Logging**: Failed authentication attempts with IP and endpoint tracking
- 🔧 **Developer Tools**: CLI commands for token generation and configuration inspection
- 🎯 **Flexible Headers**: Supports both `Authorization: Bearer` and `X-API-Token` headers
- 🔒 **Token Masking**: Secure token masking in logs and debug outputs

Installation
------------

[](#installation)

You can install the package via Composer:

```
composer require hadefication/simple-token-auth
```

The package will automatically register its service provider and configuration.

Configuration
-------------

[](#configuration)

### Publishing Configuration

[](#publishing-configuration)

Publish the configuration file to customize the package settings:

```
php artisan vendor:publish --provider="Hadefication\SimpleTokenAuth\SimpleTokenAuthServiceProvider"
```

### Environment Variables

[](#environment-variables)

Add the following to your `.env` file:

```
# Fallback token (general purpose)
API_TOKEN=your-fallback-token-here

# Service-specific tokens
API_TOKEN_SERVICE_NAME=your-service-token-here
API_TOKEN_ANOTHER_SERVICE=another-service-token-here

# Rate limiting configuration
API_RATE_LIMITING_ENABLED=true
API_RATE_LIMITING_MAX_ATTEMPTS=60
API_RATE_LIMITING_LOCKOUT_DURATION=60

# Logging configuration
API_LOG_FAILED_ATTEMPTS=true
```

### Configuration File

[](#configuration-file)

The `config/simple-token-auth.php` file contains all configuration options:

```
return [
    'tokens' => [
        'service-name' => env('API_TOKEN_SERVICE_NAME'),
        'another-service' => env('API_TOKEN_ANOTHER_SERVICE'),
    ],

    'fallback_token' => env('API_TOKEN'),

    'rate_limiting' => [
        'enabled' => env('API_RATE_LIMITING_ENABLED', true),
        'max_attempts' => env('API_RATE_LIMITING_MAX_ATTEMPTS', 60),
        'lockout_duration' => env('API_RATE_LIMITING_LOCKOUT_DURATION', 60),
    ],

    'log_failed_attempts' => env('API_LOG_FAILED_ATTEMPTS', true),
];
```

Usage
-----

[](#usage)

### Basic Middleware Usage

[](#basic-middleware-usage)

Apply the middleware to your routes:

```
// Using the middleware class directly
Route::middleware(\Hadefication\SimpleTokenAuth\Http\Middleware\SimpleTokenAuthMiddleware::class)
    ->group(function () {
        Route::get('/api/protected', function () {
            return response()->json(['message' => 'Authenticated!']);
        });
    });

// Using the registered middleware alias
Route::middleware('simple-token-auth')
    ->group(function () {
        Route::get('/api/protected', function () {
            return response()->json(['message' => 'Authenticated!']);
        });
    });
```

### Service-Specific Authentication

[](#service-specific-authentication)

Authenticate with a specific service token:

```
Route::middleware('simple-token-auth:service-name')
    ->group(function () {
        Route::get('/api/service-specific', function () {
            return response()->json(['message' => 'Service authenticated!']);
        });
    });
```

### Accessing Service Context

[](#accessing-service-context)

When using service-specific authentication, you can access the authenticated service:

```
Route::middleware('simple-token-auth:service-name')
    ->get('/api/service-data', function (Request $request) {
        $service = $request->attributes->get('authenticated_service');
        return response()->json(['service' => $service]);
    });
```

### Token Headers

[](#token-headers)

The package supports two header formats:

```
# Bearer token (recommended)
Authorization: Bearer your-token-here

# X-API-Token header (alternative)
X-API-Token: your-token-here
```

Developer Tools
---------------

[](#developer-tools)

### Generate Tokens

[](#generate-tokens)

Generate cryptographically secure tokens:

```
# Generate a fallback token
php artisan simple-token:generate

# Generate a token for a specific service
php artisan simple-token:generate my-service

# Generate with custom length
php artisan simple-token:generate my-service --length=128

# Generate with .env format output
php artisan simple-token:generate my-service --show-env

# Generate and automatically save to .env file
php artisan simple-token:generate my-service --save
```

Example output:

```
Generated token for service [my-service]:
a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6

Add the following to your .env file:
API_TOKEN_MY_SERVICE=a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6

```

With `--save` flag:

```
Generated token for service [my-service]:
a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6

Token saved to .env file as: API_TOKEN_MY_SERVICE

Next steps:
1. Add the following to your config/simple-token-auth.php file:
   'my-service' => env('API_TOKEN_MY_SERVICE'),

2. Clear config cache: php artisan config:clear

3. Verify configuration: php artisan simple-token:info

```

### Adding Generated Tokens to Configuration

[](#adding-generated-tokens-to-configuration)

After generating a token, you need to manually add it to your configuration:

#### 1. Add to .env file

[](#1-add-to-env-file)

Copy the generated token and add it to your `.env` file:

```
# For service-specific tokens
API_TOKEN_MY_SERVICE=a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6

# For fallback tokens
API_TOKEN=a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6
```

#### 2. Update config file (optional)

[](#2-update-config-file-optional)

If you want to reference the token in your `config/simple-token-auth.php` file:

```
return [
    'tokens' => [
        'my-service' => env('API_TOKEN_MY_SERVICE'),
        // Add other service tokens here
    ],

    'fallback_token' => env('API_TOKEN'),
    // ... rest of configuration
];
```

#### 3. Clear configuration cache

[](#3-clear-configuration-cache)

After updating the configuration, clear the cache:

```
php artisan config:clear
```

#### 4. Verify the token

[](#4-verify-the-token)

Use the info command to verify your token is properly configured:

```
php artisan simple-token:info
```

### Inspect Configuration

[](#inspect-configuration)

View your current token configuration:

```
php artisan simple-token:info
```

Example output:

```
Simple Token Auth Configuration:

Tokens:
  - Service: my-service, Token: my-s********oken
  - Service: another-service, Token: ano-********ther
  - Fallback Token: fall********back

Rate Limiting:
  - Enabled: Yes
  - Max Attempts: 60
  - Lockout Duration: 60 seconds

Logging:
  - Log Failed Attempts: Yes

```

Security Features
-----------------

[](#security-features)

### Timing Attack Protection

[](#timing-attack-protection)

All token comparisons use `hash_equals()` to prevent timing attacks, ensuring that comparing valid and invalid tokens takes the same amount of time.

### Rate Limiting

[](#rate-limiting)

The package implements rate limiting to protect against brute-force attacks:

- **Configurable Limits**: Set maximum attempts and lockout duration
- **IP-based Tracking**: Uses hashed IP addresses to protect privacy
- **Automatic Reset**: Rate limits are cleared on successful authentication

### Token Masking

[](#token-masking)

Tokens are automatically masked in logs and debug outputs:

- **Log Security**: Failed authentication attempts log IP and endpoint without exposing tokens
- **Debug Safety**: Configuration inspection shows masked tokens only

### Comprehensive Logging

[](#comprehensive-logging)

Failed authentication attempts are logged with:

- IP address of the requester
- Full URL that was accessed
- Timestamp of the attempt

Error Responses
---------------

[](#error-responses)

The package returns standardized JSON error responses:

### Unauthorized (401)

[](#unauthorized-401)

```
{
    "message": "Unauthenticated."
}
```

### Too Many Requests (429)

[](#too-many-requests-429)

```
{
    "message": "Too Many Attempts."
}
```

Testing
-------

[](#testing)

The package includes comprehensive tests covering:

- Token validation and generation
- Middleware functionality
- Rate limiting behavior
- Security features (timing attacks, token masking)
- Command-line tools

Run the test suite:

```
composer test
```

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details.

Security
--------

[](#security)

If you discover any security-related issues, please email  instead of using the issue tracker.

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance75

Regular maintenance activity

Popularity4

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity55

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 60% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

285d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/b9cd718c82f37ed135a350effd6b2b7c3a75a815a029bbfccbf8c777d1aa3184?d=identicon)[hadefication](/maintainers/hadefication)

---

Top Contributors

[![hadefication](https://avatars.githubusercontent.com/u/6673244?v=4)](https://github.com/hadefication "hadefication (3 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (1 commits)")

---

Tags

laravelsimple-token-auth

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/hadefication-simple-token-auth/health.svg)

```
[![Health](https://phpackages.com/badges/hadefication-simple-token-auth/health.svg)](https://phpackages.com/packages/hadefication-simple-token-auth)
```

###  Alternatives

[spatie/laravel-permission

Permission handling for Laravel 12 and up

12.9k89.8M1.0k](/packages/spatie-laravel-permission)[bezhansalleh/filament-shield

Filament support for `spatie/laravel-permission`.

2.8k2.9M88](/packages/bezhansalleh-filament-shield)[jeffgreco13/filament-breezy

A custom package for Filament with login flow, profile and teams support.

1.0k1.7M41](/packages/jeffgreco13-filament-breezy)[spatie/laravel-login-link

Quickly login to your local environment

4381.2M1](/packages/spatie-laravel-login-link)[ryangjchandler/laravel-cloudflare-turnstile

A simple package to help integrate Cloudflare Turnstile.

438896.6k2](/packages/ryangjchandler-laravel-cloudflare-turnstile)[spatie/laravel-passkeys

Use passkeys in your Laravel app

444494.4k16](/packages/spatie-laravel-passkeys)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
