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

Auth0 Php Laravel Package

auth0/auth0-php

Auth0 PHP SDK for integrating Auth0 Authentication and Management APIs. Build login/logout flows, validate tokens, and manage users, roles, and applications. Works with any PHP app, with tailored SDKs available for Laravel, Symfony, and WordPress.

View on GitHub
Deep Wiki
Context7

← Back to SDK Documentation

Getting Started

This guide will guide you through creating a simple PHP application that uses Auth0's PHP SDK to authenticate users. You could also adapt these instructions toward integrating an existing PHP application.

Pre-requisites

Composer must be installed before continuing. If you don't have it, follow this installation guide.

You will need a project directory set up to work on the demo application. This guide assumes your project is already set up with the necessary boilerplate and helper dependencies. Follow one of the following processes to get set up:

A skeleton application template is available that includes the necessary boilerplate and helper dependencies to get started.

composer create-project auth0/auth0-php:demo-skeleton auth0-php-demo
  1. Create a directory called auth0-php-demo and open a shell in that directory.

  2. Run composer init and follow the prompts to create a composer.json file.

  3. Import a dotenv and routing library into the project to simplify the demo application:

    composer require vlucas/phpdotenv nikic/fast-route
    
  4. Import a PSR-17 and PSR-18 library. Any implementations will work, but this guide will use these:

    composer require nyholm/psr7 kriswallsmith/buzz
    
  5. Create the following file structure:

    .env
    auth0.php
    public/bootstrap.php
    routes/index.php
    routes/login.php
    routes/callback.php
    routes/logout.php
    
  6. Paste the following into bootstrap.php:

    <?php
    
    // Import the Composer autoloader
    require __DIR__ . '/vendor/autoload.php';
    
    // Load the .env environment file
    $dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
    $dotenv->load();
    
    // Configure and instantiate the SDK
    require __DIR__ . '/../auth0.php';
    
    if (getenv('HTTP_HOST') !== 'localhost') {
         die('Please invoke this application from `localhost`.');
    }
    
    // Setup the routes for the application
    $dispatcher = FastRoute\simpleDispatcher(function(FastRoute\RouteCollector $r) {
        $r->addRoute('GET', '/', 'index');
        $r->addRoute('GET', '/login', 'login');
        $r->addRoute('GET', '/callback', 'callback');
        $r->addRoute('GET', '/logout', 'logout');
    });
    
    // Fetch method and URI of the incoming request
    $httpMethod = $_SERVER['REQUEST_METHOD'];
    $uri = $_SERVER['REQUEST_URI'];
    
    // Strip query string (?foo=bar) and decode URI
    if (false !== $pos = strpos($uri, '?')) {
        $uri = substr($uri, 0, $pos);
    }
    $uri = rawurldecode($uri);
    
    // Match the incoming request against the routes
    $routeInfo = $dispatcher->dispatch($httpMethod, $uri);
    switch ($routeInfo[0]) {
        case FastRoute\Dispatcher::NOT_FOUND:
            // ... 404 Not Found
            break;
        case FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
            $allowedMethods = $routeInfo[1];
            // ... 405 Method Not Allowed
            break;
        case FastRoute\Dispatcher::FOUND:
            $handler = $routeInfo[1];
            $vars = $routeInfo[2];
    
            // Include the route's matching PHP file
            require __DIR__ . '/routes/' . $handler . '.php';
            break;
    }
    
  7. Run the following command and make note of the returned string:

    openssl rand -hex 32
    
  8. Paste the following into .env:

    AUTH0_DOMAIN=
    AUTH0_CLIENT_ID=
    AUTH0_CLIENT_SECRET=
    AUTH0_COOKIE_SECRET=
    

    Set AUTH0_COOKIE_SECRET to the string returned from the previous step.

Note: Throughout this guide we will refer to the auth0-php-demo directory as the "project root".

Requirements

Environment:

Project:

  • Have a PSR-17 (HTTP factory) and PSR-18 (HTTP client) library installed.

Install the SDK

From your project root, use Composer to install the Auth0 SDK:

composer require auth0/auth0-php

Configure Auth0

If you don't already have an Auth0 account, sign up for a free one before continuing.

Open the Auth0 Dashboard's Applications section, choose "Create Application," then select "Regular Web Application," and finally, "Create."

You should then see your new application's configuration. Select the "Settings" tab.

Note the following values, as you'll need them to configure the SDK:

  • Domain
  • Client ID
  • Client Secret

You'll need to update the following application settings:

  • Application Properties:
    • Set the "Token Endpoint Authentication Method" to POST.
  • Application URIs:
    • Allowed Callback URLs — set to the URL of your application where Auth0 will redirect to during authentication, e.g., http://localhost:3000/callback.
    • Allowed Logout URLs — set to the URL of your application where Auth0 will redirect to after the user logs out, e.g., http://localhost:3000/login.

Configure the environment

Open the .env file, which will hold the demo application's configuration. Fill in each line with your Auth0 application details, which were noted in the previous step.

AUTH0_DOMAIN=
AUTH0_CLIENT_ID=
AUTH0_CLIENT_SECRET=…

Instantiate the SDK

Open the auth0.php file. You'll use this file to configure and instantiate the SDK.

<?php

use Auth0\SDK\Auth0;
use Auth0\SDK\Configuration\SdkConfiguration;

// Setup the configuration for the Auth0 PHP SDK
$configuration = new SdkConfiguration(
    domain: getenv('AUTH0_DOMAIN'),
    clientId: getenv('AUTH0_CLIENT_ID'),
    clientSecret: getenv('AUTH0_CLIENT_SECRET'),
    cookieSecret: getenv('AUTH0_COOKIE_SECRET'),
);

// Instantiate the Auth0 PHP SDK
$auth0 = new Auth0($configuration);

Our bootstrap imports this file and ensures the $auth0 variable is available to the rest of the application.

Logging in

Open the routes/login.php file. This route will start an app session and redirect the user to Auth0's Universal Login Page for authentication.

<?php

// Redirect to Auth0's Universal Login Page
header('Location: ' . $auth0->login());

Handling the callback

Open the routes/callback.php file. After authenticating with Auth0, users will be returned to the demo application at this route. The SDK handles the response and completes the authentication flow for the demo application.

<?php

// Complete the authentication flow
$auth0->exchange()

// Redirect to the index route
header('Location: /');

Logging out

Open the routes/logout.php file. This will clear the app session, and redirect to Auth0's logout endpoint. After, users are returned to the demo application.

<?php

// Redirect to Auth0's logout endpoint to complete de-authentication
header('Location: ' . $auth0->logout());

Accessing session information

Open the routes/index.php file. This will display profile information for authenticated users, or offer a login link for those who are not.

<?php

// Returns an object containing session information, or null when not authenticated
$session = $auth0->getCredentials();

// When not authenticated, offer a login link
if (null === $session) {
    echo '<p><a href="/login">Login</a></p>';
    exit;
})

// When authenticated, echo the user's profile information
echo '<p><pre>' . print_r($session->getUser(), true) . '</pre></p>';

// Offer a logout link
echo '<p><a href="/logout">Logout</a></p>';

Run the demo application

Start the PHP local development server:

php -S localhost:3000 -t public/bootstrap.php

Point your browser to http://localhost:3000 to try the demo application.

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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky