Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Airlock Laravel Package

laravel/airlock

Laravel Sanctum (formerly Airlock) offers lightweight authentication for Laravel SPAs and simple APIs. Use cookie-based session auth for first-party SPAs or issue API tokens for mobile apps and third-party clients, with minimal setup and seamless Laravel integration.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require laravel/sanctum
    php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
    php artisan migrate
    

    Add Sanctum\HasApiTokens to your User model and Authenticate middleware to api.php.

  2. First Use Case:

    • Generate a token for a user:
      $user = User::find(1);
      $token = $user->createToken('api-token')->plainTextToken;
      
    • Use the token in API requests:
      Authorization: Bearer {token}
      
  3. Key Files:

    • config/sanctum.php: Configuration for stateful domains, token expiration, and middleware.
    • app/Models/User.php: Ensure HasApiTokens is included.
    • routes/api.php: Define Sanctum routes (e.g., Sanctum::routes()).

Implementation Patterns

Common Workflows

  1. Token Generation & Management:

    • Create a token:
      $token = $user->createToken('auth-token', ['read', 'write']);
      
    • Revoke a token:
      $user->tokens()->where('name', 'auth-token')->delete();
      
    • Check token scopes:
      if ($request->user()->tokenCan('read')) { ... }
      
  2. Stateful API (SPA) Workflow:

    • Configure stateful domains in config/sanctum.php:
      'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', 'localhost,127.0.0.1')),
      
    • Use Sanctum::actingAs($user) in middleware to simulate authenticated requests.
  3. Custom Token Logic:

    • Extend HasApiTokens for custom token behavior:
      use Laravel\Sanctum\HasApiTokens;
      
      class User extends Authenticatable
      {
          use HasApiTokens;
      
          public function createCustomToken($name)
          {
              return $this->createToken($name, ['custom:scope']);
          }
      }
      
  4. Middleware Integration:

    • Protect routes with Sanctum middleware:
      Route::middleware(['auth:sanctum'])->group(function () {
          // Protected routes
      });
      
    • Customize token retrieval:
      Sanctum::getAccessTokenFromRequestUsing(function ($request) {
          return $request->bearerToken() ?: $request->cookie('sanctum');
      });
      
  5. Testing:

    • Use actingAs in tests:
      $response = $this->actingAs($user)->get('/api/user');
      
    • Mock tokens for API tests:
      $this->withHeaders(['Authorization' => 'Bearer ' . $token]);
      

Integration Tips

  1. Frontend-Specific:

    • For SPAs, use axios with Sanctum’s CSRF cookie:
      axios.get('/sanctum/csrf-cookie');
      axios.get('/api/user', { withCredentials: true });
      
    • Configure CORS in config/cors.php to allow credentials.
  2. Multi-Guard Support:

    • Use different guards for APIs and web:
      'guards' => [
          'web' => ['driver' => 'session'],
          'api' => ['driver' => 'sanctum', 'provider' => 'users'],
      ],
      
  3. Token Expiration:

    • Set default expiration in config/sanctum.php:
      'expiration' => now()->addDays(15),
      
    • Prune expired tokens with:
      php artisan sanctum:prune
      
  4. Database Optimization:

    • Add indexes to personal_access_tokens table for large-scale apps:
      Schema::table('personal_access_tokens', function (Blueprint $table) {
          $table->index(['tokenable_id', 'tokenable_type']);
          $table->index('created_at');
      });
      

Gotchas and Tips

Pitfalls

  1. CSRF Token Issues:

    • Ensure XSRF-TOKEN cookie is set for stateful requests. Use:
      Sanctum::csrfCookie();
      
    • Debug with:
      php artisan sanctum:check
      
  2. Token Not Found:

    • Verify the token is not revoked or expired. Check the expires_at column.
    • Ensure the token is attached to the correct user/guard:
      $token = $user->tokens()->where('name', 'token-name')->first();
      
  3. Stateful Domain Mismatch:

    • Requests to non-stateful domains (e.g., api.yourapp.com) won’t receive CSRF cookies. Configure explicitly:
      'stateful' => ['localhost', 'yourapp.test', 'api.yourapp.com'],
      
  4. Middleware Order:

    • Place auth:sanctum after EnsureFrontendRequestsAreStateful in api.php:
      Route::middleware(['throttle:api', 'auth:sanctum'])->group(...);
      
  5. Token Length:

    • Sanctum uses shorter tokens (60 chars) by default. For custom lengths, override the createToken method or use Str::random(80).

Debugging Tips

  1. Log Token Activity:

    • Enable last_used_at tracking in config/sanctum.php:
      'track_last_used_at' => true,
      
    • Query usage:
      $token->last_used_at; // Last activity timestamp
      
  2. Check Token Validity:

    • Validate tokens manually:
      if (Sanctum::validateToken($token, $user)) { ... }
      
  3. Database Queries:

    • Optimize token lookups by avoiding where('id', $tokenId) (use where('token', $token) instead).
  4. Environment Issues:

    • Ensure APP_URL and SANCTUM_STATEFUL_DOMAINS match your frontend’s origin. Test with:
      php artisan sanctum:check
      

Extension Points

  1. Custom Token Model:

    • Extend Laravel\Sanctum\PersonalAccessToken for custom logic:
      class CustomToken extends PersonalAccessToken
      {
          public function customMethod()
          {
              return $this->tokenable->name;
          }
      }
      
    • Update config/sanctum.php:
      'token_model' => \App\Models\CustomToken::class,
      
  2. Override Token Creation:

    • Customize token generation in User model:
      public function createToken($name, array $abilities = [])
      {
          return parent::createToken($name, $abilities)->tap(function ($token) {
              $token->abilities = serialize($abilities);
          });
      }
      
  3. Event Listeners:

    • Listen to token events (e.g., Creating, Revoked):
      use Laravel\Sanctum\Events\TokenCreated;
      
      TokenCreated::listen(function (TokenCreated $event) {
          Log::info("Token created for {$event->token->tokenable->name}");
      });
      
  4. API Resource Extensions:

    • Add token data to API responses:
      public function toArray($request)
      {
          return [
              'id' => $this->id,
              'tokens' => $this->tokens()->get()->map(fn ($token) => [
                  'name' => $token->name,
                  'abilities' => $token->abilities,
              ]),
          ];
      }
      

Configuration Quirks

  1. encrypt_cookies:

    • Set to false for performance (but lose security):
      'encrypt_cookies' => env('SANCTUM_ENCRYPT_COOKIES', false),
      
  2. prefix:

    • Disable token prefixing for compatibility:
      'prefix' => env('SANCTUM_PREFIX', null),
      
  3. stateful Domains:

    • Use wildcards for subdomains:
      'stateful' => ['*.yourdomain.com'],
      
  4. token_blacklist_enabled:

    • Enable to revoke tokens immediately (requires laravel/framework v9.2+):
      'token_blacklist_enabled' => true,
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony