DEV Community

Cover image for Laravel Bastion: Stripe-Style API Authentication for Laravel
Laravel Mastery
Laravel Mastery

Posted on

Laravel Bastion: Stripe-Style API Authentication for Laravel

Ever wished Laravel had API tokens as elegant as Stripe's? Meet Laravel Bastion by Steve McDougall.

What is Bastion?
Bastion brings Stripe-inspired API key management to Laravel with prefixed tokens, environment isolation, and granular permissions.

app_test_pk_xxxxxxxxxxxxx
app_live_sk_xxxxxxxxxxxxx
Enter fullscreen mode Exit fullscreen mode

🌍 Environment Isolation

Separate test and live environments prevent accidental key leaks.
🎯 Granular Scopes

['posts:read', 'posts:write', 'users:*']
Enter fullscreen mode Exit fullscreen mode

πŸ” Three Token Types

Public keys (client-side safe)
Secret keys (server-side only)
Restricted keys (limited scopes)

πŸ“Š Built-in Audit Logging

Track every token action for security and compliance.

Quick Start

  1. Add the trait:
use JustSteveKing\Bastion\Concerns\HasBastionTokens;

class User extends Authenticatable
{
    use HasBastionTokens;
}
Enter fullscreen mode Exit fullscreen mode
  1. Create a token:
$result = $user->createBastionToken(
    name: 'My API Key',
    scopes: ['posts:read'],
    environment: TokenEnvironment::Test,
    type: TokenType::Restricted,
);
Enter fullscreen mode Exit fullscreen mode
  1. Protect routes:
Route::middleware(AuthenticateToken::class)->group(function () {
    Route::get('/api/posts', [PostController::class, 'index']);
});
Enter fullscreen mode Exit fullscreen mode
  1. Use CLI commands:
php artisan bastion:generate {user-id} "Token Name"
php artisan bastion:rotate {token-id}
php artisan bastion:revoke {token-id}
Enter fullscreen mode Exit fullscreen mode

Why Bastion?

Choose Bastion when you need:

Multi-environment isolation
Fine-grained permissions
Enterprise-grade security
Stripe-like developer experience

Perfect for SaaS platforms, fintech apps, and third-party APIs.
Get started: Laravel Bastion on GitHub

πŸ“– Read the full in-depth article on Medium: Laravel Bastion: Complete Guide

laravel #php #api #authentication

Top comments (0)