A lightweight package that simplifies API token management in your Laravel applications. It provides Artisan commands and middleware support to create, manage, and authenticate API tokens efficiently.
- Create API tokens: Generate and store new API tokens.
- List API tokens: View existing tokens with their details.
- Delete API tokens: Remove existing tokens with confirmation prompts.
- Middleware integration: Secure your API routes with a simple token-based authentication middleware.
Install the package via Composer:
composer require matbcvo/laravel-token-auth
Publish the migration files to your application's database/migrations
directory:
php artisan vendor:publish --provider="Matbcvo\LaravelTokenAuth\LaravelTokenAuthServiceProvider" --tag=migrations
Run the migrations to create the api_tokens
table in your database:
php artisan migrate
To secure your routes using the provided middleware, you can authenticate API requests based on a token.
The package registers a middleware alias auth.token
. You can use this alias:
use Illuminate\Support\Facades\Route;
Route::middleware('auth.token')->group(function () {
Route::get('/protected-route', function () {
return response()->json(['message' => 'You have access to this route!']);
});
});
You can use the middleware class directly for explicit clarity:
use Illuminate\Support\Facades\Route;
use Matbcvo\LaravelTokenAuth\Http\Middleware\AuthenticateApiToken;
Route::middleware(AuthenticateApiToken::class)->group(function() {
Route::get('/protected-route', function () {
return response()->json(['message' => 'You have access to this route!']);
});
});
This package provides the following Artisan commands:
To generate and save a new API token, use the following command:
php artisan api-token:create {name} {--expires=}
Parameters:
-
name
(required): This is the descriptive name for the token, useful for identifying its purpose. -
--expires
(optional): The token's expiration time in minutes. If not provided, the token will not expire.
View all existing API tokens:
php artisan api-token:list
Delete a specific API token by its ID:
php artisan api-token:delete {id}
You’ll be asked to confirm before deletion.
The package provides a configuration file to customize its behavior. To publish the configuration file, run:
php artisan vendor:publish --provider="Matbcvo\LaravelTokenAuth\LaravelTokenAuthServiceProvider" --tag=config
The configuration file includes the following options:
-
Token length
Defines the length of the API token. By default, it is set to 60 characters.
'token_length' => 60,
Contributions are welcome! If you encounter issues or have feature requests, please submit them via GitHub issues.
This package is open-source and available under the MIT License.