Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Laravel Bastion - A Stripe-inspired API authentication package

Published on by

Laravel Bastion - A Stripe-inspired API authentication package image

Laravel Bastion is a Stripe-inspired API authentication package created by Steve McDougall with environment isolation, granular scopes, built-in security, and more.

Features

  • Stripe-style API Tokens - Prefixed tokens with environment indicators (app_test_pk_, app_live_sk_)
  • Environment Isolation - Separate test and live environments with automatic validation
  • Granular Scopes - Fine-grained permission control with wildcard support
  • Token Types - Public, Secret, and Restricted keys with different access levels
  • Audit Logging - Comprehensive activity tracking for compliance and debugging
  • Webhook Support - Built-in webhook endpoints with signature verification
  • Security First - Expiration dates and secure token hashing
  • Laravel Native - Built with Laravel conventions and best practices

After installing this package, you'll want to ensure you add the HasBastionTokens trait to your User model:

use JustSteveKing\Bastion\Concerns\HasBastionTokens;
 
class User extends Authenticatable
{
use HasBastionTokens;
 
// ...
}

Then, to generate a token, you can:

use JustSteveKing\Bastion\Enums\TokenEnvironment;
use JustSteveKing\Bastion\Enums\TokenType;
 
$result = $user->createBastionToken(
name: 'LN API Key',
scopes: ['posts:read', 'posts:write'],
environment: TokenEnvironment::Test,
type: TokenType::Restricted,
);
 
$token = $result['plainTextToken'];
// Example: app_test_rk_a8Kx7mN2pQ4vW9yB1cD3eF5gH6jK8lM
 
echo "Token: " . $token;

To protect your routes, Bastion provides the AuthenticateToken middleware:

use JustSteveKing\Bastion\Http\Middleware\AuthenticateToken;
 
Route::middleware(AuthenticateToken::class)->group(function () {
Route::get('/api/posts', [PostController::class, 'index']);
});

And when sending requests to an authenticated endpoint, you should pass the token via the Authorization header using the Bearer schema:

use GuzzleHttp\Client;
 
$client = new Client(['base_uri' => 'https://example.com/api']);
$token = 'YOUR_BEARER_TOKEN';
 
$response = $client->request('GET', '/posts', [
'headers' => [
'Authorization' => 'Bearer ' . $token,
'Accept' => 'application/json',
],
]);

If you also need to rotate your tokens, then Bastion has you covered. Use the rotate() method:

$result = $token->rotate();

And there is even an option to use the CLI:

php artisan bastion:rotate {token-id}

Speaking of the CLI, Bastion allows you to manage your tokens using various Artisan commands:

# Generate tokens
php artisan bastion:generate {user-id} "LN App Token" \
--environment=test \
--type=restricted \
--scopes=posts:read --scopes=posts:write
 
# Revoke tokens
php artisan bastion:revoke {token-id} --reason="Token no longer used"
 
# Prune expired tokens
php artisan bastion:prune-tokens --expired
 
# and more...

Steve has put together a handy package with a good set of features. To learn more about Bastion, its features, and view the source code, hop on over to the GitHub repository.

Yannick Lyn Fatt photo

Staff Writer at Laravel News and Full stack web developer.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Tinkerwell

Enjoy coding and debugging in an editor designed for fast feedback and quick iterations. It's like a shell for your application – but with multi-line editing, code completion, and more.

Visit Tinkerwell
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Laravel Cloud logo

Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Cloud
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Flaky Test Retries in Pest v4.5.0 image

Flaky Test Retries in Pest v4.5.0

Read article
Debugging production Laravel apps without losing your mind image

Debugging production Laravel apps without losing your mind

Read article
Passage: A Lightweight API Proxy Gateway for Laravel image

Passage: A Lightweight API Proxy Gateway for Laravel

Read article
PestPHP Intellisense in Laravel VS Code Extension v1.7.0 image

PestPHP Intellisense in Laravel VS Code Extension v1.7.0

Read article
Drop in comments for Filament with Commentions image

Drop in comments for Filament with Commentions

Read article
Laravel Starter Kits Now Include Toast Notifications image

Laravel Starter Kits Now Include Toast Notifications

Read article