Add Authorization to Your Laravel Application

Auth0's Laravel SDK allows you to quickly add token-based authorization and route access control to your Laravel application. This guide demonstrates how to integrate Auth0 with a new (or existing) Laravel 9 or 10 application.


Backend applications differ from traditional web applications in that they do not handle user authentication or have a user interface. They provide an API that other applications can interact with. They accept access tokens from Authorization headers in requests to control access to routes.

Separate front-end applications are usually built to interact with these types of backends. These can be anything from single-page applications or native or mobile apps (all of which Auth0 also provides SDKs for!)

When users need to interact with your backend application, they first authenticate with Auth0 using the frontend application. The frontend application then retrieves an access token from Auth0, which it can use to make requests to your backend application on behalf of the user.

As their name implies, access tokens are designed to address matters of access control (authorization), and do not contain information about the user. Backend applications work exclusively with access tokens. You can retrieve information about the user who created the token using the Management API, which we will demonstrate later.

1

Laravel Installation

If you do not already have a Laravel application set up, open a shell to a suitable directory for a new project and run the following command:

composer create-project --prefer-dist laravel/laravel auth0-laravel-api ^9.0

Was this helpful?

/

All the commands in this guide assume you are running them from the root of your Laravel project, directory so you should cd into the new project directory:

cd auth0-laravel-api

Was this helpful?

/
2

SDK Installation

Run the following command within your project directory to install the Auth0 Laravel SDK:

composer require auth0/login:^7.8 --update-with-all-dependencies

Was this helpful?

/

Then generate an SDK configuration file for your application:

php artisan vendor:publish --tag auth0

Was this helpful?

/
3

SDK Configuration

Run the following command from your project directory to download the Auth0 CLI:

curl -sSfL https://raw.githubusercontent.com/auth0/auth0-cli/main/install.sh | sh -s -- -b .

Was this helpful?

/

Then authenticate the CLI with your Auth0 account, choosing "as a user" when prompted:

./auth0 login

Was this helpful?

/

Next, create a new application with Auth0:

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

Was this helpful?

/

You should also create a new API:

./auth0 apis create \
  --name "My Laravel Backend API" \
  --identifier "https://github.com/auth0/laravel-auth0" \
  --offline-access \
  --no-input \
  --json > .auth0.api.json

Was this helpful?

/

This produces two files in your project directory that configure the SDK.

As these files contain credentials it's important to treat these as sensitive. You should ensure you do not commit these to version control. If you're using Git, you should add them to your .gitignore file:

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

Was this helpful?

/
4

Access Control

The SDK automatically registers its authorization guard with your Laravel application for use with the api middleware, which by default Laravel applies to all routes in your application's routes/api.php file.

You can use the Auth0 SDK's authorization guard to restrict access to your application's routes.

To reject requests that do not contain a valid access token in the Authorization header, you can use Laravel's auth middleware:

Route::get('/private', function () {
  return response()->json([
    'message' => 'Your token is valid; you are authorized.',
  ]);
})->middleware('auth');

Was this helpful?

/

You can also require the provided token to have specific permissions by combining this with Laravel's can middleware:

Route::get('/scope', function () {
    return response()->json([
      'message' => 'Your token is valid and has the `read:messages` permission; you are authorized.',
    ]);
})->middleware('auth')->can('read:messages');

Was this helpful?

/
5

Token Information

Information about the provided access token is available through Laravel's Auth Facade, or the auth() helper function.

For example, to retrieve the user's identifier and email address:

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

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

Was this helpful?

/
6

Retrieve User Information

You can retrieve information about the user who created the access token from Auth0 using the Auth0 Management API. The SDK provides a convenient wrapper for this API, accessible through the SDK's management() method.

Before making Management API calls you must enable your application to communicate with the Management API. This can be done from the Auth0 Dashboard's API page, choosing Auth0 Management API, and selecting the 'Machine to Machine Applications' tab. Authorize your Laravel application, and then click the down arrow to choose the scopes you wish to grant.

For the following example, you should grant the read:users scope. A list of API endpoints and the required scopes can be found in the Management API documentation.

use Auth0\Laravel\Facade\Auth0;

Route::get('/me', function () {
  $user = auth()->id();
  $profile = cache()->get($user);

  if (null === $profile) {
    $endpoint = Auth0::management()->users();
    $profile = $endpoint->get($user);
    $profile = Auth0::json($profile);

    cache()->put($user, $profile, 120);
  }

  $name = $profile['name'] ?? 'Unknown';
  $email = $profile['email'] ?? 'Unknown';

  return response()->json([
    'name' => $name,
    'email' => $email,
  ]);
})->middleware('auth');

Was this helpful?

/
7

Run the Application

You are now ready to start your Laravel application, so it can accept requests:

php artisan serve

Was this helpful?

/
8

Retrieve a Test Token

You can learn more about retrieving access tokens here. For this quickstart, however, you can simply use an access token from your API settings' "test" view.

Checkpoint

Open a shell and try issuing requests to your application.

Begin by requesting the public route:

curl --request GET \
  --url http://localhost:8000/api \
  --header 'Accept: application/json'

Was this helpful?

/

Next, use your access token in an Authorization header to request a protected route:

curl --request GET \
  --url http://localhost:8000/api/private \
  --header 'Accept: application/json' \
  --header 'Authorization: Bearer YOUR_ACCESS_TOKEN'

Was this helpful?

/

Finally, try requesting the scope-protected route, which will only succeed if the access token has the read:messages scope granted:

curl --request GET \
  --url http://localhost:8000/api/scope \
  --header 'Accept: application/json' \
  --header 'Authorization: Bearer YOUR_ACCESS_TOKEN'

Was this helpful?

/

Additional Reading

  • User Repositories and Models extends the Auth0 Laravel SDK to use custom user models, and how to store and retrieve users from a database.
  • Hooking Events covers how to listen for events raised by the Auth0 Laravel SDK, to fully customize the behavior of your integration.
  • Management API support is built into the Auth0 Laravel SDK, allowing you to interact with the Management API from your Laravel application.

Next Steps

Excellent work! If you made it this far, you should now have login, logout, and user profile information running in your application.

This concludes our quickstart tutorial, but there is so much more to explore. To learn more about what you can do with Auth0, check out:

Did it work?

Any suggestion or typo?

Edit on GitHub
Sign Up

Sign up for an or to your existing account to integrate directly with your own tenant.