### Install Laravel Bastion Package Source: https://github.com/juststeveking/laravel-bastion/blob/main/README.md Installs the Laravel Bastion package using Composer. ```bash composer require juststeveking/laravel-bastion ``` -------------------------------- ### Install Laravel Bastion Package Source: https://context7.com/juststeveking/laravel-bastion/llms.txt These bash commands illustrate how to install the Laravel Bastion package using Composer and publish its configuration and migration files using Artisan. It also shows the command to run the migrations and outlines the steps for adding the `HasBastionTokens` trait to your User model. ```bash # Install via Composer composer require juststeveking/laravel-bastion # Run installation command (interactive) php artisan bastion:install # This will: # 1. Publish config/bastion.php # 2. Publish database migrations # 3. Prompt to run migrations # Manual steps php artisan vendor:publish --tag=bastion-config php artisan vendor:publish --tag=bastion-migrations php artisan migrate # Add trait to User model ``` -------------------------------- ### Run Laravel Bastion Installation Command Source: https://github.com/juststeveking/laravel-bastion/blob/main/README.md Runs the Artisan command to publish configuration, migrations, and optionally run migrations for Laravel Bastion. ```bash php artisan bastion:install ``` -------------------------------- ### Make Authenticated API Request Source: https://github.com/juststeveking/laravel-bastion/blob/main/README.md Example of how to make an authenticated request to an API endpoint using a Bearer token. ```bash curl -H "Authorization: Bearer app_test_rk_..." \ https://your-api.com/api/users ``` -------------------------------- ### Bastion Configuration Options (PHP) Source: https://github.com/juststeveking/laravel-bastion/blob/main/README.md Example of the Bastion configuration file, showing key options for customizing table names, token expiration, audit log retention, rate limits, security settings, error response format, and the user model. ```php return [ // Table names (customizable) 'tables' => [ 'tokens' => 'bastion_tokens', 'audit_logs' => 'bastion_audit_logs', 'webhooks' => 'bastion_webhook_endpoints', ], // Token expiration (days) 'token_expiration_days' => null, // Audit log retention (days) 'audit_log_retention_days' => 90, // Rate limits per minute 'rate_limits' => [ 'test' => 100, 'live' => 60, ], // Security settings 'security' => [ 'prevent_test_tokens_in_production' => true, 'enable_audit_logging' => true, 'enable_alerting' => true, ], // Error response format 'errors' => [ 'use_rfc7807' => true, // RFC 7807 Problem Details 'base_url' => 'https://bastion.laravel.com/errors/', // Base for problem type URLs ], // User model 'user_model' => App\Models\User::class, ]; ``` -------------------------------- ### Query Audit Logs - PHP Source: https://github.com/juststeveking/laravel-bastion/blob/main/README.md Queries audit logs to retrieve information about API requests. Examples include fetching recent activity for a specific token or finding failed requests within a given time frame. ```php use JustSteveKing\Bastion\Models\AuditLog; // Get recent activity for a token $logs = AuditLog::where('bastion_token_id', $token->id) ->latest() ->take(100) ->get(); // Find failed requests $failures = AuditLog::where('status_code', '>=', 400) ->where('created_at', '>=', now()->subDay()) ->get(); ``` -------------------------------- ### Integrate HasBastionTokens Trait in User Model Source: https://context7.com/juststeveking/laravel-bastion/llms.txt This PHP code demonstrates how to integrate the `HasBastionTokens` trait into your `User` model in Laravel to enable Bastion token functionalities. It shows how to use the `bastionTokens()` relationship and the `createBastionToken()` method, along with an example of accessing and displaying user tokens. ```php // app/Models/User.php use JustSteveKing\Bastion\Concerns\HasBastionTokens; class User extends Authenticatable { use HasBastionTokens; // Now user has bastionTokens() relationship // and createBastionToken() method } // Access user tokens $user = User::find(1); $tokens = $user->bastionTokens()->get(); foreach ($tokens as $token) { echo "{$token->name}: {$token->token_prefix}\n"; } ``` -------------------------------- ### Publish Bastion Configuration (Laravel Artisan) Source: https://github.com/juststeveking/laravel-bastion/blob/main/README.md Command to publish the Laravel Bastion configuration file to your application's config directory. This allows for customization of various settings related to tokens, logs, and security. ```bash php artisan vendor:publish --tag=bastion-config ``` -------------------------------- ### Create Webhook Endpoint - PHP Source: https://github.com/juststeveking/laravel-bastion/blob/main/README.md Creates a new webhook endpoint to receive real-time notifications. Requires user ID, URL, events to listen to, environment, and active status. Returns the signing secret. ```php use JustSteveKing\Bastion\Models\WebhookEndpoint; $result = WebhookEndpoint::createEndpoint([ 'user_id' => $user->id, 'url' => 'https://your-app.com/webhooks/bastion', 'events' => ['token.created', 'token.revoked', 'token.used'], 'environment' => TokenEnvironment::Live, 'is_active' => true, ]); // Store the signing secret securely! $signingSecret = $result['signingSecret']; // Example: whsec_a8Kx7mN2pQ4vW9yB1cD3eF5gH6jK8lM ``` -------------------------------- ### Configure Laravel Bastion Package Source: https://context7.com/juststeveking/laravel-bastion/llms.txt This PHP code snippet shows the configuration options for the Laravel Bastion package, which can be customized via the published `config/bastion.php` file. It covers table names, token expiration, rate limits, webhook settings, security configurations, and error handling formats. ```php // config/bastion.php return [ // Custom table names 'tables' => [ 'tokens' => 'bastion_tokens', 'audit_logs' => 'bastion_audit_logs', 'webhooks' => 'bastion_webhook_endpoints', ], // Token expiration (null = no expiration) 'token_expiration_days' => 365, // Audit log retention 'audit_log_retention_days' => 90, // Rate limits per minute 'rate_limits' => [ 'test' => 100, 'live' => 60, ], // Webhook configuration 'webhooks' => [ 'timeout' => 30, 'max_failures' => 10, 'retry_delay' => 60, ], // Security settings 'security' => [ 'prevent_test_tokens_in_production' => true, 'enable_audit_logging' => true, 'enable_alerting' => true, ], // RFC 7807 Problem Details error format 'errors' => [ 'use_rfc7807' => true, 'base_url' => 'https://api.example.com/errors/', ], // User model association 'user_model' => App\Models\User::class, ]; // Publish configuration // php artisan vendor:publish --tag=bastion-config // RFC 7807 error response example: /* { "type": "https://api.example.com/errors/insufficient_scope", "title": "Forbidden", "status": 403, "detail": "Missing required scope: payments:refund", "instance": "/api/payments/123/refund", "required_scope": "payments:refund" } */ ``` -------------------------------- ### Bastion Environment Enum Source: https://github.com/juststeveking/laravel-bastion/blob/main/README.md Illustrates the use of TokenEnvironment enum for Test and Live environments in Bastion. ```php TokenEnvironment::Test TokenEnvironment::Live ``` -------------------------------- ### Schedule Artisan Commands (PHP) Source: https://github.com/juststeveking/laravel-bastion/blob/main/README.md Defines how to schedule the bastion:prune-tokens and bastion:prune-logs Artisan commands within Laravel's Console Kernel. This ensures automated cleanup of tokens and logs on a daily or weekly basis. ```php protected function schedule(Schedule $schedule): void { $schedule->command('bastion:prune-tokens --expired')->daily(); $schedule->command('bastion:prune-logs')->weekly(); } ``` -------------------------------- ### Listen to Token Lifecycle Events in PHP Source: https://context7.com/juststeveking/laravel-bastion/llms.txt This snippet shows how to use Laravel's Event facade to listen for various token lifecycle events such as creation, usage, revocation, rotation, and expiration. It demonstrates logging and email notifications for custom business logic and security. ```php use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Log; use JustSteveKing\Bastion\Events{ TokenCreated, TokenUsed, TokenRevoked, TokenRotated, TokenExpired }; use App\Mail\TokenRevokedNotification; // EventServiceProvider.php public function boot(): void { // Log token creation Event::listen(TokenCreated::class, function (TokenCreated $event) { Log::info('API token created', [ 'token_id' => $event->token->id, 'user_id' => $event->token->user_id, 'environment' => $event->token->environment->value, 'type' => $event->token->type->value, 'scopes' => $event->token->scopes, 'plain_text_token' => $event->plainTextToken, // Only in TokenCreated ]); }); // Monitor token usage Event::listen(TokenUsed::class, function (TokenUsed $event) { Log::debug('Token used', [ 'token_id' => $event->token->id, 'ip_address' => $event->ipAddress, 'user_agent' => $event->userAgent, 'endpoint' => $event->endpoint, ]); }); // Send notification on revocation Event::listen(TokenRevoked::class, function (TokenRevoked $event) { Mail::to($event->token->user) ->send(new TokenRevokedNotification($event->token, $event->reason)); Log::warning('Token revoked', [ 'token_id' => $event->token->id, 'reason' => $event->reason, ]); }); // Track token rotation for audit Event::listen(TokenRotated::class, function (TokenRotated $event) { Log::info('Token rotated', [ 'old_token_id' => $event->oldToken->id, 'new_token_id' => $event->newToken->id, ]); }); } ``` -------------------------------- ### Verify Webhook Signatures for Authenticity (PHP) Source: https://context7.com/juststeveking/laravel-bastion/llms.txt This PHP code demonstrates how to set up a route to receive webhook requests and verify their authenticity using the provided signature and timestamp. It includes steps to extract headers, find the corresponding webhook endpoint, and use the `verifySignature` method, which also guards against replay attacks by checking the timestamp. ```php use Illuminate\Support\Facades\Route; use Illuminate\Http\Request; use JustSteveKing\Bastion\Models\WebhookEndpoint; Route::post('/webhooks/bastion', function (Request $request) { // Extract signature headers $signature = $request->header('X-Bastion-Signature'); $timestamp = (int) $request->header('X-Bastion-Timestamp'); $payload = $request->getContent(); // Find endpoint by secret prefix (stored in your database) $secretPrefix = 'a8Kx7mN2'; // Extract from your storage $endpoint = WebhookEndpoint::where('secret_prefix', $secretPrefix)->first(); if (!$endpoint) { abort(404, 'Webhook endpoint not found'); } // Verify signature (includes replay attack prevention) if (!$endpoint->verifySignature($payload, $signature, $timestamp)) { abort(401, 'Invalid webhook signature'); } // Process webhook event $event = $request->input('event'); $data = $request->input('data'); match ($event) { 'token.created' => handleTokenCreated($data), 'token.revoked' => handleTokenRevoked($data), 'token.used' => handleTokenUsed($data), 'token.expired' => handleTokenExpired($data), default => logger()->warning("Unknown webhook event: {$event}"), }; return response()->json(['received' => true]); }); // Replay attack prevention: verifySignature() rejects requests // with timestamps older than 5 minutes (300 seconds) ``` -------------------------------- ### Create Webhook Endpoints for Token Events (PHP) Source: https://context7.com/juststeveking/laravel-bastion/llms.txt This snippet illustrates how to create webhook endpoints in Laravel Bastion to receive real-time notifications for token events like creation, revocation, or usage. It details the required parameters, including user ID, URL, events to subscribe to, environment, and active status. It also highlights the importance of securely storing the generated signing secret. ```php use JustSteveKing\Bastion\Models\WebhookEndpoint; use JustSteveKing\Bastion\Enums\TokenEnvironment; use App\Models\User; // Create webhook endpoint $user = User::find(1); $result = WebhookEndpoint::createEndpoint([ 'user_id' => $user->id, 'url' => 'https://your-app.com/webhooks/bastion', 'events' => ['token.created', 'token.revoked', 'token.used', 'token.expired'], 'environment' => TokenEnvironment::Live, 'is_active' => true, ]); $endpoint = $result['endpoint']; $signingSecret = $result['signingSecret']; // CRITICAL: Store signing secret securely - shown only once // Example: whsec_a8Kx7mN2pQ4vW9yB1cD3eF5gH6jK8lM echo "Webhook URL: " . $endpoint->url . "\n"; echo "Secret: " . $signingSecret . "\n"; echo "Events: " . implode(', ', $endpoint->events); // Webhook payload example /* { "event": "token.created", "data": { "token_id": 123, "token_prefix": "a8Kx7mN2", "user_id": 1, "environment": "live", "type": "restricted", "scopes": ["users:read", "users:write"] }, "timestamp": 1697001600 } */ ``` -------------------------------- ### Create Token with Scopes - PHP Source: https://github.com/juststeveking/laravel-bastion/blob/main/README.md Creates a new Bastion token for a user with specified scopes. Supports granting specific permissions, using wildcards for category-level access, or full access. ```php // Grant specific permissions $user->createBastionToken( name: 'User Manager', scopes: ['users:read', 'users:write'], ); // Use wildcards for category-level access $user->createBastionToken( name: 'Payment API', scopes: ['payments:*'], // All payment operations ); // Full access $user->createBastionToken( name: 'Admin Token', scopes: ['*'], // All scopes ); ``` -------------------------------- ### Generate Token - Artisan CLI Source: https://github.com/juststeveking/laravel-bastion/blob/main/README.md Generates a new Bastion token via the Artisan CLI. Allows specifying user ID, token name, environment, type, and multiple scopes. ```bash php artisan bastion:generate {user-id} "Token Name" \ --environment=test \ --type=restricted \ --scopes=users:read --scopes=users:write ``` -------------------------------- ### Create API Tokens with Laravel Bastion Source: https://context7.com/juststeveking/laravel-bastion/llms.txt Generates a new API token for a user with specified scopes, environment, and token type. The plain text token and token model are returned. Ensure to store the plain text token securely as it is only displayed once. ```php use JustSteveKing\Bastion\Enums\{TokenEnvironment, TokenType}; use App\Models\User; // Create a restricted test token with specific scopes $user = User::find(1); $result = $user->createBastionToken( name: 'Mobile App Integration', scopes: ['users:read', 'users:write', 'payments:read'], environment: TokenEnvironment::Test, type: TokenType::Restricted, ); // Store this token securely - it's only shown once $plainTextToken = $result['plainTextToken']; $tokenModel = $result['token']; echo "Token: " . $plainTextToken; // Output: app_test_rk_a8Kx7mN2pQ4vW9yB1cD3eF5gH6jK8lM0nP2qR4sT6u // Create a live secret key with full access $liveResult = $user->createBastionToken( name: 'Backend Server', scopes: ['*'], environment: TokenEnvironment::Live, type: TokenType::Secret, ); echo "Live token: " . $liveResult['plainTextToken']; // Output: app_live_sk_z9Xy8wV7uT6sR5qP4oN3mL2kJ1iH0gF9e ``` -------------------------------- ### Query Audit Logs with PHP Source: https://context7.com/juststeveking/laravel-bastion/llms.txt This snippet demonstrates how to query comprehensive audit logs using the AuditLog model provided by Laravel Bastion. It covers filtering by token, time, errors, user, environment, resource type, and response time, aiding in compliance, debugging, and security monitoring. ```php use JustSteveKing\Bastion\Models\AuditLog; use JustSteveKing\Bastion\Enums\TokenEnvironment; // Get recent activity for a specific token $token = BastionToken::find(1); $logs = AuditLog::where('bastion_token_id', $token->id) ->latest() ->take(100) ->get(); foreach ($logs as $log) { echo "{$log->created_at}: {$log->method} {$log->endpoint} - {$log->status_code}\n"; } // Find failed requests in last 24 hours $failures = AuditLog::errors() ->where('created_at', '>=', now()->subDay()) ->get(); // Query with scopes $userActivity = AuditLog::forUser(1) ->recent(days: 7) ->successful() ->get(); // Get all payment operations in test environment $paymentLogs = AuditLog::environment(TokenEnvironment::Test) ->forResource(type: 'payment', id: 123) ->get(); // Find slow requests (response time > 1000ms) $slowRequests = AuditLog::where('response_time_ms', '>', 1000) ->orderBy('response_time_ms', 'desc') ->take(50) ->get(); // Audit log includes: method, endpoint, status_code, ip_address, // user_agent, request/response data, response_time_ms, error_message ``` -------------------------------- ### Manage Tokens via Artisan CLI Source: https://context7.com/juststeveking/laravel-bastion/llms.txt This snippet shows how to use Artisan commands provided by Laravel Bastion to manage API tokens. It covers generating tokens with specific scopes and environments, revoking tokens by ID or prefix, rotating tokens, and pruning expired or unused tokens and audit logs. ```bash # Generate token for a user php artisan bastion:generate 1 "Production API" \ --environment=live \ --type=secret \ --scopes=users:read \ --scopes=users:write \ --scopes=payments:* # Output: Token created: app_live_sk_z9Xy8wV7uT6sR5qP... # Revoke single token by ID php artisan bastion:revoke 123 --reason="Security incident" # Revoke by token prefix php artisan bastion:revoke abc12345 --reason="Integration deprecated" # Revoke all tokens for user php artisan bastion:revoke 0 --all-user=456 --reason="User offboarded" # Rotate token php artisan bastion:rotate 123 # Prune expired tokens php artisan bastion:prune-tokens --expired # Prune tokens unused for 90 days php artisan bastion:prune-tokens --days=90 # Prune old audit logs (default: 90 days from config) php artisan bastion:prune-logs # Custom audit log retention php artisan bastion:prune-logs --days=30 # Schedule in app/Console/Kernel.php protected function schedule(Schedule $schedule): void { $schedule->command('bastion:prune-tokens --expired')->daily(); $schedule->command('bastion:prune-logs')->weekly(); } ``` -------------------------------- ### Rotate Token - Artisan CLI Source: https://github.com/juststeveking/laravel-bastion/blob/main/README.md Rotates a token using the Artisan command-line interface by providing the token ID. ```bash php artisan bastion:rotate {token-id} ``` -------------------------------- ### Listen to Token Events - PHP Source: https://github.com/juststeveking/laravel-bastion/blob/main/README.md Listens to various token lifecycle events dispatched by Bastion. Allows custom logic to be executed when tokens are created, used, revoked, rotated, or expired. ```php use JustSteveKing\Bastion\Events{ TokenCreated, TokenUsed, TokenRevoked, TokenRotated, TokenExpired }; // Listen to events in your EventServiceProvider Event::listen(TokenCreated::class, function (TokenCreated $event) { // $event->token - The BastionToken model // $event->plainTextToken - The plain text token (only in TokenCreated) Log::info('Token created', ['token_id' => $event->token->id]); }); Event::listen(TokenUsed::class, function (TokenUsed $event) { // $event->token // $event->ipAddress // $event->userAgent // $event->endpoint }); Event::listen(TokenRevoked::class, function (TokenRevoked $event) { // $event->token // $event->reason Mail::to($event->token->user)->send(new TokenRevokedNotification($event)); }); ``` -------------------------------- ### RFC 7807 Error Base URL Configuration (PHP) Source: https://github.com/juststeveking/laravel-bastion/blob/main/README.md Shows how to configure the base URL for RFC 7807 Problem Details error responses within the Bastion configuration file. This allows for customization of the error type URIs returned by the API. ```php // config/bastion.php 'errors' => [ 'use_rfc7807' => true, 'base_url' => 'https://bastion.laravel.com/errors/', ], ``` -------------------------------- ### Protect Routes with AuthenticateToken Middleware Source: https://github.com/juststeveking/laravel-bastion/blob/main/README.md Secures routes using the AuthenticateToken middleware. You can also specify required scopes directly in the middleware definition. ```php use JustSteveKing\Bastion\Http\Middleware\AuthenticateToken; Route::middleware(AuthenticateToken::class)->group(function () { Route::get('/api/users', [UserController::class, 'index']); }); // Require specific scope Route::middleware([AuthenticateToken::class . ':users:write']) ->post('/api/users', [UserController::class, 'store']); ``` -------------------------------- ### Protect Routes with Laravel Bastion Token Authentication Source: https://context7.com/juststeveking/laravel-bastion/llms.txt Secures API routes using middleware to authenticate requests and enforce scope requirements. Supports basic authentication, specific scope validation, multiple middleware stacks including audit logging, and wildcard scope matching. ```php use Illuminate\Support\Facades\Route; use JustSteveKing\Bastion\Http\Middleware\{AuthenticateToken, AuditApiRequest}; use App\Http\Controllers\{UserController, PaymentController}; // Basic authentication - any valid token Route::middleware(AuthenticateToken::class)->group(function () { Route::get('/api/profile', [UserController::class, 'profile']); }); // Require specific scope Route::middleware([AuthenticateToken::class . ':users:write']) ->post('/api/users', [UserController::class, 'store']); // Multiple middleware with audit logging Route::middleware([AuthenticateToken::class . ':payments:refund', AuditApiRequest::class]) ->post('/api/payments/{id}/refund', [PaymentController::class, 'refund']); // Wildcard scope matching Route::middleware([AuthenticateToken::class . ':payments:*']) ->prefix('/api/payments') ->group(function () { Route::get('/', [PaymentController::class, 'index']); Route::post('/', [PaymentController::class, 'create']); Route::post('/{id}/refund', [PaymentController::class, 'refund']); }); // Making authenticated API requests with curl // curl -H "Authorization: Bearer app_test_rk_a8Kx..." https://api.example.com/api/users // curl "https://api.example.com/api/users?api_key=app_test_rk_a8Kx..." ``` -------------------------------- ### Bastion Token Types Enum Source: https://github.com/juststeveking/laravel-bastion/blob/main/README.md Demonstrates the usage of TokenType enum for Public, Secret, and Restricted keys in Bastion. ```php TokenType::Public TokenType::Secret TokenType::Restricted ``` -------------------------------- ### Prune Unused Tokens (Laravel Artisan) Source: https://github.com/juststeveking/laravel-bastion/blob/main/README.md Command to prune API tokens that have not been used for a specified number of days. This helps in cleaning up old or potentially compromised tokens. It requires the 'days' option to be set. ```bash php artisan bastion:prune-tokens --days=90 ``` -------------------------------- ### Generate a Bastion Token Source: https://github.com/juststeveking/laravel-bastion/blob/main/README.md Creates a new Bastion token for a user with specified name, scopes, environment, and token type. The plain text token is returned only once and should be stored securely. ```php use JustSteveKing\Bastion\Enums\TokenEnvironment; use JustSteveKing\Bastion\Enums\TokenType; $result = $user->createBastionToken( name: 'My API Key', scopes: ['users:read', 'users:write'], environment: TokenEnvironment::Test, type: TokenType::Restricted, ); // Store this securely - it's only shown once! $token = $result['plainTextToken']; // Example: app_test_rk_a8Kx7mN2pQ4vW9yB1cD3eF5gH6jK8lM echo "Token: " . $token; ``` -------------------------------- ### Enable API Request Auditing - PHP Source: https://github.com/juststeveking/laravel-bastion/blob/main/README.md Enables comprehensive API request auditing by applying the `AuditApiRequest` middleware along with `AuthenticateToken`. All requests within the group will be logged, capturing details like method, path, status, IP, and token information. ```php use JustSteveKing\Bastion\Http\Middleware{AuthenticateToken, AuditApiRequest}; Route::middleware([AuthenticateToken::class, AuditApiRequest::class]) ->group(function () { // All requests will be logged Route::get('/api/users', [UserController::class, 'index']); }); ``` -------------------------------- ### Verify Webhook Signature - PHP Source: https://github.com/juststeveking/laravel-bastion/blob/main/README.md Verifies incoming webhook requests by checking the signature, timestamp, and payload. Aborts with 401 if the signature is invalid. Assumes the endpoint secret is stored. ```php use JustSteveKing\Bastion\Models\WebhookEndpoint; Route::post('/webhooks/bastion', function (Request $request) { $endpoint = WebhookEndpoint::where('secret_prefix', '...')->first(); $signature = $request->header('X-Bastion-Signature'); $timestamp = $request->header('X-Bastion-Timestamp'); $payload = $request->getContent(); if (!$endpoint->verifySignature($payload, $signature, (int)$timestamp)) { abort(401, 'Invalid signature'); } // Process webhook... $event = $request->input('event'); $data = $request->input('data'); return response()->json(['received' => true]); }); ``` -------------------------------- ### Validate Token Permissions with Scopes and Wildcards (PHP) Source: https://context7.com/juststeveking/laravel-bastion/llms.txt This snippet demonstrates how to check if a Bastion token has specific permissions using scopes. It supports exact scope matching, wildcard scopes (e.g., 'users:*'), and a global wildcard ('*') for broad access. This is useful for implementing granular access control in controllers. ```php use JustSteveKing\Bastion\Models\BastionToken; $token = BastionToken::findByToken('app_test_rk_a8Kx...'); // Check specific scope if ($token->hasScope('users:read')) { // Allow user read operations } // Wildcard scopes - 'users:*' grants all user operations if ($token->hasScope('users:delete')) { // This returns true if token has 'users:*' or 'users:delete' } // Global wildcard - '*' grants everything if ($token->hasScope('payments:create')) { // This returns true if token has '*', 'payments:*', or 'payments:create' } // Example: Controller authorization public function destroy(User $user, Request $request) { $token = $request->bastionToken; if (!$token->hasScope('users:delete')) { abort(403, 'Insufficient permissions'); } $user->delete(); return response()->json(['message' => 'User deleted']); } ``` -------------------------------- ### Rotate Tokens with Laravel Bastion Source: https://context7.com/juststeveking/laravel-bastion/llms.txt Enhances security by rotating tokens, which creates a new token while automatically revoking the old one. This process can be done programmatically or via a CLI command. Metadata about the rotation is stored for auditing. ```php use JustSteveKing\Bastion\Models\BastionToken; // Rotate programmatically $token = BastionToken::find(1); $result = $token->rotate(); $newToken = $result['plainTextToken']; $newTokenModel = $result['token']; echo "New token: " . $newToken; // Output: app_test_rk_b9Lz8mN3pQ5vW7yC1dE4fG6hJ8kL9mN // Old token is automatically revoked // Metadata includes rotation history $metadata = $newTokenModel->metadata; // ['rotated_from' => 1, 'rotated_at' => '2025-10-11T10:30:00Z'] // CLI rotation command // php artisan bastion:rotate 1 // Output: Token rotated successfully. New token: app_test_rk_b9Lz... ``` -------------------------------- ### Add HasBastionTokens Trait to User Model Source: https://github.com/juststeveking/laravel-bastion/blob/main/README.md Integrates Laravel Bastion's token management capabilities into your User model by using the HasBastionTokens trait. ```php use JustSteveKing\Bastion\Concerns\HasBastionTokens; class User extends Authenticatable { use HasBastionTokens; // ... } ``` -------------------------------- ### Prune Old Audit Logs (Laravel Artisan) Source: https://github.com/juststeveking/laravel-bastion/blob/main/README.md Command to remove old audit log entries based on a retention period. This helps manage database size by deleting logs older than a specified number of days. It can use the default retention period or a custom one. ```bash # Use config default (90 days) php artisan bastion:prune-logs # Custom retention period php artisan bastion:prune-logs --days=30 ``` -------------------------------- ### Revoke Token - Artisan CLI Source: https://github.com/juststeveking/laravel-bastion/blob/main/README.md Revokes Bastion tokens using the Artisan CLI. Can revoke by token ID, token prefix, or all tokens for a specific user. Allows specifying a reason for revocation. ```bash # Revoke by token ID php artisan bastion:revoke 123 --reason="Security incident" # Revoke by token prefix php artisan bastion:revoke abc12345 --reason="No longer needed" # Revoke all tokens for a user php artisan bastion:revoke 0 --all-user=456 --reason="User offboarded" ``` -------------------------------- ### Rotate Token - PHP Source: https://github.com/juststeveking/laravel-bastion/blob/main/README.md Rotates an existing token, creating a new one and revoking the old one. The result contains the new plain text token and the token model. The old token is automatically revoked. ```php $result = $token->rotate(); // Get the new token (store securely) $newToken = $result['plainTextToken']; $newTokenModel = $result['token']; // The old token is automatically revoked ``` -------------------------------- ### Prune Expired Tokens - Artisan CLI Source: https://github.com/juststeveking/laravel-bastion/blob/main/README.md Prunes expired Bastion tokens using the Artisan CLI. The `--expired` flag targets only expired tokens. ```bash # Prune expired tokens php artisan bastion:prune-tokens --expired ``` -------------------------------- ### Revoke Bastion Tokens Programmatically and via CLI (PHP & CLI) Source: https://context7.com/juststeveking/laravel-bastion/llms.txt This section shows how to revoke Bastion access tokens using PHP code or Artisan CLI commands. It covers revoking single tokens, all tokens for a user, and provides options to include a reason for revocation. It also includes a check to see if a token has been revoked (soft deleted). ```php use JustSteveKing\Bastion\Models\BastionToken; // Revoke a single token $token = BastionToken::find(1); $token->revoke(reason: 'Security incident - potential compromise'); // Revoke all tokens for a user $user = User::find(1); foreach ($user->bastionTokens()->get() as $token) { $token->revoke(reason: 'User offboarded'); } // Check if token is revoked (soft deleted) if ($token->trashed()) { return response()->json(['error' => 'Token has been revoked'], 401); } ``` ```bash // CLI commands // Revoke by token ID // php artisan bastion:revoke 123 --reason="Security incident" // Revoke by token prefix // php artisan bastion:revoke abc12345 --reason="No longer needed" // Revoke all tokens for a user // php artisan bastion:revoke 0 --all-user=456 --reason="User offboarded" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.