Weave 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

Auth0 Php Laravel Package

auth0/auth0-php

The official Auth0 PHP SDK for Authentication and Management APIs. Build PHP 8.2+ apps with PSR-18/17/7 HTTP support and tailored Laravel, Symfony, and WordPress SDKs. Includes quickstarts for session-based web apps and token-protected backend APIs.

View on GitHub
Deep Wiki
Context7

Getting Started

  1. Install via Composer:
    composer require auth0/auth0-php
    
  2. Configure .env (Laravel):
    AUTH0_DOMAIN=your-tenant.auth0.com
    AUTH0_CLIENT_ID=...
    AUTH0_CLIENT_SECRET=...
    AUTH0_COOKIE_SECRET=$(openssl rand -hex 32)
    AUTH0_CALLBACK_URL=https://your-app.test/auth0/callback
    
  3. Bind the SDK in a service provider (recommended for Laravel):
    // AppServiceProvider::register()
    $this->app->singleton(Auth0::class, function () {
        return new Auth0(new SdkConfiguration(
            domain: config('auth0.domain'),
            clientId: config('auth0.client_id'),
            clientSecret: config('auth0.client_secret'),
            cookieSecret: config('auth0.cookie_secret'),
            redirectUri: config('auth0.callback_url'),
        ));
    });
    
  4. First use case – protect a route:
    Route::get('/dashboard', function () {
        $auth0 = app(Auth0::class);
        $creds = $auth0->getCredentials();
        if (! $creds || $creds->accessTokenExpired) {
            return redirect($auth0->login());
        }
        return view('dashboard', ['user' => $creds->user]);
    })->middleware('web');
    

Implementation Patterns

Authentication Workflow

  • Login – redirect to $auth0->login().
  • Callback – exchange the code:
    Route::get('/auth0/callback', function (Auth0 $auth0) {
        if ($auth0->getExchangeParameters()) {
            $auth0->exchange();
            return redirect('/dashboard');
        }
        return redirect('/login');
    });
    
  • User access – $credentials = $auth0->getCredentials(); $user = $credentials?->user;

Management API Integration (v9.5+)

The SDK now exposes Application Profiles, CAPTCHA policies, and client search alongside existing endpoints.

  • Initialise the management client:
    use Auth0\SDK\Management\Auth0ManagementClient;
    $mgmt = new Auth0ManagementClient(
        domain: config('auth0.domain'),
        clientId: config('auth0.client_id'),
        clientSecret: config('auth0.client_secret'),
        scope: ['read:users','update:users','read:clients','create:clients','read:captcha_policies']
    );
    
  • Search clients (new):
    $clients = $mgmt->clients->search([
        'q' => 'name:"My App"',
        'per_page' => 10,
    ]);
    
  • Application Profiles (new):
    $profile = $mgmt->applicationProfiles->create([
        'name' => 'My Profile',
        'description' => '...',
    ]);
    
  • CAPTCHA policies (new):
    $policy = $mgmt->captchaPolicies->create([
        'name' => 'Bot Protection',
        'enabled' => true,
    ]);
    
  • Removed: experiment status endpoints – remove any calls to them and migrate to supported endpoints or custom logic.

Token Validation (Stateless APIs)

Use the SDK’s token helper (e.g., Auth0\SDK\Token) or a JWT library. Example with firebase/php-jwt:

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

$decoded = JWT::decode($request->bearerToken(), new Key($publicKey, 'RS256'));
// Validate issuer, audience, expiry

Custom Claims

Custom claims are added via Auth0 Actions/Rules, not the SDK. After login, the $credentials->user object includes custom claims if configured in the ID token. Example Auth0 Action:

exports.onExecutePostLogin = async (event, api) => {
  api.idToken.setCustomClaim('https://myapp.com/roles', event.user.app_metadata.roles);
};

Then access in Laravel: $user->{'https://myapp.com/roles'}.

Token Refresh & Renewal

  • Renewal now verifies and validates the ID token returned by renew(). Ensure your Auth0 tenant’s signing keys are correctly configured and the aud/iss match.
  • Implement middleware for silent refresh:
    public function handle($request, Closure $next) {
        $auth0 = app(Auth0::class);
        if ($auth0->getCredentials()?->accessTokenExpired) {
            $auth0->renew(); // now validates ID token
        }
        return $next($request);
    }
    

Gotchas and Tips

Breaking / Behavioural Changes in 9.5.0

  • Experiment status endpoints removed – if you used them, migration is required.
  • renew() now validates ID token – previously it returned tokens without verification. This may cause failures if your ID token is invalid (e.g., clock skew, wrong audience). Test renew() in staging.
  • CookieStore hardening – undecryptable cookies are now cleared instead of throwing. Users with corrupted cookies will be silently logged out. Monitor logs for related warnings.
  • New API scopes – Application Profiles, CAPTCHA policies, and client search require additional Management API scopes (e.g., read:clients, create:clients, read:captcha_policies). Update your Auth0 application’s granted scopes.

Common Pitfalls

  • Callback URL mismatch – must be identical in Auth0 Dashboard and SDK config (including trailing slash, http vs https).
  • Cookie secret – use a 32-byte random string; never commit it.
  • Token expiry – always check accessTokenExpired before using credentials; leverage renew() but be aware of the new validation.

Debugging

  • Enable SDK debug logging:
    $config = new SdkConfiguration(..., debug: true);
    
    Logs go to storage/logs/laravel.log.
  • Decode JWTs manually for inspection:
    composer require firebase/php-jwt
    
    $decoded = JWT::decode($token, new Key($key, 'RS256'));
    
  • Catch Management API exceptions:
    try {
        $mgmt->users->get('user_id');
    } catch (\Auth0\SDK\Exception\SdkException $e) {
        report($e);
    }
    

Extension Points

  • Custom HTTP client for retries/logging:
    $http = new \GuzzleHttp\Client(['timeout' => 10]);
    $config = new SdkConfiguration(..., httpClient: $http);
    
  • Middleware for auto-refresh (see pattern above).
  • Custom user model – extend Laravel’s User with an auth0_id column and sync on callback.

Performance

  • Cache Management API responses with Cache::remember.
  • Use field selection: $mgmt->users->get($id, ['fields' => ['email','name']]).
  • Batch operations (e.g., deleteUsers) where available.

Security

  • Never hardcode secrets – use .env / Laravel’s encrypted config.
  • Secure cookies:
    cookieSettings: ['secure' => true, 'httpOnly' => true, 'sameSite' => 'Lax']
    
  • Rate-limit Auth0 API calls via Laravel’s RateLimiter.
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.
labyrinthe/connect-php
encore2/laravel-admin2
cboxdk/laravel-console-kit
shapecode/doctrine-dbal-datetimeutc
gilads-otiannoh254/inertia-protocol
dakiquang/laravel-oauth-refresh-lock
woda/laravel-worktrees
dalefranks/ramasite
faghy/laracashbook
roundly-consulting/google-places-for-laravel
roundly-consulting/kubernetes-api-for-laravel
roundly-consulting/plausible-for-laravel
gvp/gvp-laravel-template
metasyncsite/laravel-metasync-client
roundly-consulting/onboarding-for-laravel
adachsoft/cli-process-tester
adachsoft/changelog-linter
adachsoft/collection
adachsoft/php-code-style
adachsoft/api-version-bundle