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

Workos Laravel Package

laravel/workos

Laravel utilities used by Laravel starter kits to integrate WorkOS AuthKit. Provides the glue for authentication flows and configuration so you can add WorkOS-powered login to a Laravel app quickly and consistently.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require laravel/workos
    

    Add the WorkOS service provider to config/app.php:

    'providers' => [
        // ...
        Laravel\Workos\WorkosServiceProvider::class,
    ],
    
  2. Configuration: Publish the config file:

    php artisan vendor:publish --provider="Laravel\Workos\WorkosServiceProvider" --tag="config"
    

    Update .env with your WorkOS credentials:

    WORKOS_API_KEY=your_api_key_here
    WORKOS_SECRET_KEY=your_secret_key_here
    
  3. First Use Case: Integrate WorkOS AuthKit into your Laravel app by extending the WorkosAuthKit facade:

    use Laravel\Workos\Facades\WorkosAuthKit;
    
    // Verify a user's session
    $user = WorkosAuthKit::verifySession();
    
    // Redirect to WorkOS login if needed
    if (!$user) {
        return redirect()->away(WorkosAuthKit::loginUrl());
    }
    

Key Entry Points

  • WorkosAuthKit facade: Central interface for authentication flows.
  • Middleware: Use workos.auth middleware to protect routes.
  • Event listeners: Extend WorkosEvents for custom logic (e.g., user provisioning).

Implementation Patterns

Core Workflows

  1. Authentication Flow:

    • Login: Redirect users to WorkOS via WorkosAuthKit::loginUrl().
    • Callback: Handle the /workos/callback route (configured in routes/web.php):
      Route::get('/workos/callback', [WorkosAuthKit::class, 'handleCallback']);
      
    • Session Verification: Use WorkosAuthKit::verifySession() in controllers/middleware.
  2. User Provisioning:

    • Listen to Workos\Events\UserProvisioned to sync WorkOS users with your database:
      WorkosAuthKit::provisionUser($workosUser, function ($workosUser) {
          return User::firstOrCreate([
              'email' => $workosUser->email,
          ]);
      });
      
  3. Directory Sync:

    • Fetch and sync WorkOS directories (e.g., for SSO groups):
      $directories = WorkosAuthKit::getDirectories();
      foreach ($directories as $directory) {
          // Map to your local groups/roles
      }
      

Integration Tips

  • Laravel Starter Kits: Leverage the Laravel starter kits for pre-built integrations (e.g., Jetstream + WorkOS).
  • Custom Claims: Extend WorkosAuthKit to add custom claims to tokens:
    WorkosAuthKit::extendClaims(function ($user) {
        return ['custom_claim' => 'value'];
    });
    
  • Testing: Use the WorkosAuthKit mock in tests:
    WorkosAuthKit::shouldReceive('verifySession')->andReturn($mockUser);
    

Middleware Usage

Protect routes with the built-in middleware:

Route::middleware(['workos.auth'])->group(function () {
    // Protected routes
});

Gotchas and Tips

Pitfalls

  1. API Key Misconfiguration:

    • Ensure WORKOS_API_KEY and WORKOS_SECRET_KEY are set in .env and match WorkOS dashboard credentials.
    • Debug Tip: Check config/workos.php for overrides and validate keys there.
  2. Callback Route Conflicts:

    • The /workos/callback route must be publicly accessible. Avoid naming conflicts with other routes.
    • Fix: Use route model binding or explicit path checks:
      Route::get('/workos/callback', [WorkosAuthKit::class, 'handleCallback'])
           ->name('workos.callback');
      
  3. Session Expiry:

    • WorkOS sessions expire. Handle Workos\Exceptions\SessionExpired gracefully:
      try {
          $user = WorkosAuthKit::verifySession();
      } catch (SessionExpired $e) {
          return redirect()->away(WorkosAuthKit::loginUrl());
      }
      
  4. Directory Sync Delays:

    • WorkOS directory syncs may lag. Cache results or implement retry logic:
      $directories = Cache::remember('workos.directories', now()->addHours(1), function () {
          return WorkosAuthKit::getDirectories();
      });
      

Debugging

  • Log WorkOS Responses: Enable debug mode in config/workos.php:

    'debug' => env('WORKOS_DEBUG', false),
    

    Logs will appear in storage/logs/laravel.log.

  • Token Validation: If tokens fail validation, verify:

    • The WORKOS_SECRET_KEY is correct.
    • The token was issued by WorkOS (check iss claim).
    • The token hasn’t expired (check exp claim).

Extension Points

  1. Custom Providers: Override the default WorkOS provider by binding a custom implementation:

    $this->app->bind(
        Laravel\Workos\Contracts\WorkosProvider::class,
        App\Services\CustomWorkosProvider::class
    );
    
  2. Event Hooks: Extend the WorkosEvents class to add custom logic:

    WorkosAuthKit::on('user.provisioned', function ($user) {
        // Custom logic (e.g., send welcome email)
    });
    
  3. Token Claims: Modify claims before they’re sent to WorkOS:

    WorkosAuthKit::extendClaims(function ($user) {
        return [
            'department' => $user->department,
            'is_admin' => $user->isAdmin(),
        ];
    });
    

Configuration Quirks

  • Environment Overrides: Use WORKOS_* env vars to override config values (e.g., WORKOS_API_URL for custom WorkOS instances).
  • HTTPS Requirement: WorkOS enforces HTTPS for callback URLs. Test locally with:
    APP_URL=https://localhost
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport