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

Laravel Laravel Package

auth0-samples/laravel

A Laravel sample app demonstrating Auth0 integration, including login/logout, user profiles, protected routes, and SDK configuration. Use it as a reference for adding Auth0 authentication to Laravel applications.

View on GitHub
Deep Wiki
Context7

Getting Started

This repo is a demonstration application, not a distributable package — do not composer require auth0-samples/laravel. Treat it as a reference implementation you clone, read, and cherry-pick from.

Clone and run:

git clone https://github.com/auth0-samples/laravel.git my-app
cd my-app
cp .env.example .env
composer install
php artisan key:generate

Then provision Auth0:

  1. Create a Regular Web Application in the Auth0 dashboard.
  2. Set Allowed Callback URLs → http://localhost:8000/auth0/callback
  3. Set Allowed Logout URLs → http://localhost:8000
  4. Set Allowed Web Origins → http://localhost:8000
  5. Copy Domain, Client ID, Client Secret into .env (as AUTH0_DOMAIN, AUTH0_CLIENT_ID, AUTH0_CLIENT_SECRET, AUTH0_REDIRECT_URI). Generate a 32+ char AUTH0_COOKIE_SECRET.

Then:

php artisan migrate
php artisan serve

Where to look first: in order — .env.example (the actual contract), config/auth.php (guard/provider wiring to the auth0 driver), the routes file (SDK auto-registers /auth0/login, /auth0/logout, /auth0/callback), and the login/dashboard views. The vendor/auth0/login source is where the real behaviour lives — grep it when the sample feels opaque.

First use case: hit /login, complete the Auth0 Universal Login redirect, land on the dashboard, read Auth::user() claims, then hit /logout and confirm you're bounced to Auth0's /v2/logout and back.

Implementation Patterns

  • Make the guard the default for web sessions. In config/auth.php, set 'defaults' => ['guard' => 'auth0'] (or keep web as default and put protected routes behind auth:auth0). This lets you use idiomatic auth()->user(), Auth::check(), and Route::middleware('auth') without any controller-level glue.

  • Protect route groups, not individual actions:

    Route::middleware(['auth'])->group(function () {
        Route::get('/dashboard', [DashboardController::class, 'index']);
    });
    
  • Read claims from the user object, not the session. The SDK returns an Auth0\Laravel\User (a generic-user contract, not an Eloquent model). Access claims with array-style or getAttribute() access — Auth::user()->getAttribute('sub'), ->getAttribute('email'), ->getAttribute('https://myapp/roles') for namespaced custom claims. Do not assume ->save(), relations, or ->id on the primary key.

  • Use sub as your stable identifier. Emails change; sub (auth0|abc123) is immutable. If you persist users to your DB, key off sub and treat the Auth0 object as a projection.

  • Separate web and API auth into different route groups. Web sessions use StatefulMiddleware (with session/cookie state). Bearer-token APIs use StatelessMiddleware. Do not put a stateless token route inside the web middleware group or you'll pay for session bootstrapping and get cookie/CSRF confusion.

  • Extend user shape via a custom repository. If you need roles, permissions, or a local profile table, implement Auth0\Laravel\Contract\Model\UserRepository (or the version-appropriate interface) and bind it in a service provider. This is the sanctioned extension point for hydrating users from your own DB on each login.

  • Log out with Auth0, not just locally. route('logout') posts to the SDK's logout endpoint, which clears the local session and redirects to /v2/logout. If you only Auth::logout(), the Auth0 SSO cookie remains and the next login silently re-authenticates. Configure AUTH0_LOGOUT_REDIRECT_URI to control the post-logout landing.

  • Keep custom routes thin. The SDK owns the callback handler. Do not reimplement /auth0/callback; put post-login side effects (welcome email, audit log) into a user.authenticated style event listener or middleware that runs after authentication.

Gotchas and Tips

  • AUTH0_DOMAIN must be bare. your-tenant.auth0.com, not https://your-tenant.auth0.com. The SDK builds URLs by prefixing the scheme; including it double-prefixes and produces opaque discovery/JWKS fetch failures that look like network errors.

  • AUTH0_COOKIE_SECRET is the #1 silent failure. Version 7+ encrypts the transient login state (nonce, state, PKCE verifier) into a cookie. Too short, missing, or changed between requests produces a generic "invalid state" error on callback with no clue in the logs. Generate 32+ random bytes and keep it stable per environment.

  • Session driver cannot be array. The state cookie is separate from the Laravel session, but the stateful middleware still relies on the session being coherent across the redirect round-trip. SESSION_DRIVER=array (or clearing cookies mid-flow) breaks login intermittently.

  • After any .env change, run php artisan config:clear. The SDK caches discovery documents and JWKS. config:cache in production is fine as long as the values were correct when cached — a stale cached config with old AUTH0_DOMAIN is a common "it works locally, not on staging" cause.

  • Token audience mismatches fail loudly on API routes, quietly on web. For stateless/bearer validation you must issue tokens with an audience claim matching your API identifier and use RS256. HS256 tokens, or tokens with the wrong audience, throw InvalidTokenException. There is no fallback to session auth on those routes.

  • actingAs() does not work with the Auth0 guard out of the box. For feature tests, either bind a fake UserRepository in the container that returns a stub user, or mock the auth0 guard. Trying to Auth::actingAs($user) on the SDK guard typically fails because it doesn't implement stateful session injection the way Eloquent's guard does.

  • Do not upgrade Laravel blindly. The sample pins Laravel 9; the underlying auth0/login SDK has its own Laravel version matrix. Upgrading to 10/11 requires checking SDK compatibility and re-reading the CHANGELOG — middleware names and interface signatures have changed across major versions.

  • Middleware ordering matters. If you write custom middleware that reads Auth::user(), place it after the SDK's stateful middleware has run. In Laravel this usually means registering it in the web group after Authenticate, or via route middleware inside a auth group.

  • Namespaced custom claims need the full URI. Auth0 rules/actions that add https://myapp.com/roles produce a claim key of exactly that string. Auth::user()->getAttribute('roles') returns null. Use $user->getAttribute('https://myapp.com/roles').

  • Extension surface is small and worth knowing: UserRepositoryInterface (hydration), the Auth0\Laravel\Facade\Auth0 facade (tenant-level operations like Management API calls — requires a separate M2M token, not the client secret), and event listeners on login/logout. Almost everything else you'd want to customize goes through those three doors or a thin middleware.

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.
diephp/sequences
users-au/socialite-provider
twidpay/twid-logger
mrnewport/laravel-plaid
mrnewport/laravel-repo
mrnewport/laravel-docsign
mrnewport/laravel-stow
mrnewport/laravel-flow
mrnewport/laravel-priceable
mrnewport/laravel-nestedterms
fredmeng/laravel-apidoc-generator
itstructure/laravel-multilingual-tools
pdustdar/elasticsearch
markupai/php-sdk
rlacerda83/lumem-microservice-shipment
uni-method/symfony-lib
tacticmedia/scim-server-bundle
neika-ai/symfony-bundle
mattleads/agent-publishing-bundle
glavweb/framework-bundle