Skip to content

Laravel SDK for Auth0 Authentication and Management APIs.

License

Notifications You must be signed in to change notification settings

Piestar/laravel-auth0

 
 

Repository files navigation

laravel-auth0

Build Status Code Coverage Total Downloads License

Requirements

Your application must use a supported Laravel version, and your environment must run a supported PHP version. We do not support versions of Laravel or PHP that are no longer supported by their maintainers.

SDK Laravel PHP Supported Until
7.5+ 10 8.2+ Feb 2025
8.1+ Nov 2024
7.0+ 9 8.2+ Feb 2024
8.1+ Feb 2024
8.0+ Nov 2023

You will also need Composer and an Auth0 account.

Installation

Using Quickstart (Fastest)
  • Run the following command to create a new Laravel 9 project pre-configured with the SDK:

    composer create-project auth0-samples/laravel auth0-laravel-app

Using Composer
  1. Run the following command in your project directory to install the SDK:

    composer require auth0/login:^7.8 --update-with-all-dependencies
  2. Generate an SDK configuration file for your application:

    php artisan vendor:publish --tag auth0

Configuration

Using JSON (Fastest)
  1. Download the Auth0 CLI to your project directory:

    Note
    If you are using the Quickstart, skip to the next step.

    curl -sSfL https://raw.githubusercontent.com/auth0/auth0-cli/main/install.sh | sh -s -- -b .
  2. Authenticate with your Auth0 account:

    ./auth0 login
  3. Register a new application with Auth0:

    ./auth0 apps create \
        --name "My Laravel Application" \
        --type "regular" \
        --auth-method "post" \
        --callbacks "http://localhost:8000/callback" \
        --logout-urls "http://localhost:8000" \
        --reveal-secrets \
        --no-input \
        --json > .auth0.app.json
  4. Register a new API with Auth0:

    ./auth0 apis create \
        --name "My Laravel Application API" \
        --identifier "https://github.com/auth0/laravel-auth0" \
        --offline-access \
        --no-input \
        --json > .auth0.api.json
  5. Add the new files to .gitignore:

    echo ".auth0.*.json" >> .gitignore

Using Environment Variables
  1. Download the Auth0 CLI to your project directory:

    Note
    If you are using the Quickstart, skip to the next step.

    curl -sSfL https://raw.githubusercontent.com/auth0/auth0-cli/main/install.sh | sh -s -- -b .
  2. Authenticate with your Auth0 account:

    ./auth0 login
  3. Register a new application with Auth0:

    ./auth0 apps create \
        --name "My Laravel Application" \
        --type "regular" \
        --auth-method "post" \
        --callbacks "http://localhost:8000/callback" \
        --logout-urls "http://localhost:8000" \
        --reveal-secrets \
        --no-input

    Make a note of the client_id and client_secret values in the output.

  4. Register a new API with Auth0:

    ./auth0 apis create \
        --name "My Laravel Application API" \
        --identifier "https://github.com/auth0/laravel-auth0" \
        --offline-access \
        --no-input
  5. Open the .env file in your project directory. Add the following lines, replacing the values with the ones you noted in the previous steps:

    # The Auth0 domain for your tenant (e.g. tenant.region.auth0.com):
    AUTH0_DOMAIN=...
    
    # The application `client_id` you noted above:
    AUTH0_CLIENT_ID=...
    
    # The application `client_secret` you noted above:
    AUTH0_CLIENT_SECRET=...
    
    # The API `identifier` you used above:
    AUTH0_AUDIENCE=...

    Additional variables are available. More on those in the configuration guide.

Quickstarts

Examples

Authentication

The SDK automatically registers all the necessary authentication services within the web middleware group for your application. Once you have configured the SDK your users will be able to authenticate with your application using Auth0.

The SDK automatically registers the following routes to facilitate authentication:

Route Purpose
/login Initiates the authentication flow.
/logout Logs the user out.
/callback Handles the callback from Auth0.

Note
See the configuration guide for information on customizing this behavior.


Access Control

The SDK automatically registers its authentication and authorization guards within the web and api middleware groups for your Laravel application.

To require a user to be authenticated to access a route, use Laravel's auth middleware:

Route::get('/private', function () {
  return response('Welcome! You are logged in.');
})->middleware('auth');

You can also require that the user have specific permissions to access a route, using Laravel's can middleware:

Route::get('/scope', function () {
    return response('You have the `read:messages` permissions, and can therefore access this resource.');
})->middleware('auth')->can('read:messages');

Note
Permissions require that RBAC be enabled within your API settings.


Users and Tokens

Laravel's Auth Facade (or the auth() global helper) can be used to retrieve information about the authenticated user, or the access token used to authorize the request.

For example, for routes using the web middleware group in routes/web.php:

Route::get('/', function () {
  if (! auth()->check()) {
    return response('You are not logged in.');
  }

  $user = auth()->user();
  $name = $user->name ?? 'User';
  $email = $user->email ?? '';

  return response("Hello {$name}! Your email address is {$email}.");
});

Alternatively, for routes using the api middleware group in routes/api.php:

Route::get('/', function () {
  if (! auth()->check()) {
    return response()->json([
      'message' => 'You did not provide a token.',
    ]);
  }

  return response()->json([
    'message' => 'Your token is valid; you are authorized.',
    'id' => auth()->id(),
    'token' => auth()?->user()?->getAttributes(),
  ]);
});

Management API

You can issue Auth0 Management API calls through the SDK's management() method.

Note
Before your application can make calls to the Management API, you must enable your application to communicate with the Management API or configure the SDK with a management token.

For example, you can update a user's metadata by calling the management()->users()->update() method:

use Auth0\Laravel\Facade\Auth0;

Route::get('/colors', function () {
  $colors = ['red', 'blue', 'green', 'black', 'white', 'yellow', 'purple', 'orange', 'pink', 'brown'];

  // Update the authenticated user with a randomly assigned favorite color.
  Auth0::management()->users()->update(
    id: auth()->id(),
    body: [
        'user_metadata' => [
            'color' => $colors[random_int(0, count($colors) - 1)]
        ]
    ]
  );

  // Retrieve the user's updated profile.
  $profile = Auth0::management()->users()->get(auth()->id());

  // For interoperability, the SDK returns all API responses as
  // PSR-7 Responses that contain the JSON response.

  // You can use the `json()` helper to unpack the PSR-7, and
  // convert the API's JSON response to a native PHP array.
  $profile = Auth0::json($profile);

  // Read the user's profile.
  $color = $profile['user_metadata']['color'] ?? 'unknown';
  $name = auth()->user()->name;

  return response("Hello {$name}! Your favorite color is {$color}.");
})->middleware('auth');

All the SDK's Management API methods are documented here.

Documentation

You may also find the following resources helpful:

Contributions to improve our documentation are welcomed.

Community

The Auth0 Community is where you can get support, ask questions, and share your projects.

Contributing

We appreciate feedback and contributions to this library. Before you get started, please review Auth0's General Contribution guidelines.

The Contribution Guide contains information about our development process and expectations, insight into how to propose bug fixes and improvements, and instructions on how to build and test changes to the library.

To provide feedback or report a bug, please raise an issue.

Code of Conduct

Participants are expected to adhere to Auth0's Code of Conduct when interacting with this project.

Security

If you believe you have found a security vulnerability, we encourage you to responsibly disclose this and not open a public issue. We will investigate all reports. The Responsible Disclosure Program details the procedure for disclosing security issues.

License

This library is open-sourced software licensed under the MIT license.


Auth0 Logo

Auth0 is an easy-to-implement, adaptable authentication and authorization platform.
To learn more, check out "Why Auth0?"

About

Laravel SDK for Auth0 Authentication and Management APIs.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • PHP 100.0%