English
  • Deutsch
  • English
  • Français
  • Español
  • Português
  • 日本語
lumen logo
php logo
api
authorization

Lumen PHP Authorization: Basic API Access Control

api
authorization
Dan Arias
By Dan Arias, R&D Engineering ManagerLast update on November 19, 2021

This PHP code sample demonstrates how to implement authorization in a Lumen API server using Auth0. This code sample shows you how to accomplish the following tasks:

  • Register a Lumen API in the Auth0 Dashboard.

  • Use Lumen middleware to enforce API security policies.

  • Perform access control in Lumen using a token-based authorization strategy powered by JSON Web Tokens (JWTs).

  • Validate access tokens in JSON Web Token (JWT) format using Lumen middleware.

  • Make authenticated requests to a secure Lumen API server.

Code Sample Specs

This code sample uses the following main tooling versions:

  • Lumen v8.3.1
  • PHP v7.4.25
  • Auth0 PHP SDK v8.0.3

The Lumen project dependency installations were tested with Composer v2.1.14.

Quick Auth0 Set Up

First and foremost, if you haven't already, sign up for an Auth0 account to connect your API with the Auth0 Identity Platform.

Next, you need to create an API registration in the Auth0 Dashboard. You'll get two configuration values, the Auth0 Audience and the Auth0 Domain, that will help connect your API server with Auth0. You'll also need a test access token to practice making secure calls to your API.

Get the Auth0 audience

  • Open the APIs section of the Auth0 Dashboard.

  • Click on the Create API button and fill out the "New API" form with the following values:

Name
Hello World API Server
Identifier
https://hello-world.example.com
  • Click on the Create button.

Visit the "Register APIs" document for more details.

When setting up APIs, we also refer to the API identifier as the Audience value. Store that value in the following field to set up your API server in the next section:

Get an Auth0 access token

You can get an access token from the Auth0 Dashboard to test making a secure call to your protected API endpoints:

  • On the Auth0 API page, click on the "Test" tab.

If this is the first time that you are setting up a testing application, click on the "Create & Authorize Test Application" button.

  • Locate the section called "Response" and click on the copy button on the top-right corner.

  • Paste the access token value in the following field so that you can use it in the next sections to test your API server:

When you enter a value in the input fields present on this page, any code snippet that uses such value updates to reflect it. Using the input fields makes it easy to copy and paste code as you follow along. For security, these values are stored in memory and only used locally. They are gone as soon as you refresh the page! As an extra precaution, you should use values from an Auth0 test application instead of a production one.

Get the Auth0 domain

Now, follow these steps to get the Auth0 Domain value.

  • Open the Auth0 Domain Settings

  • Locate the bold text in the page description that follows this pattern: tenant-name.region.auth0.com. That's your Auth0 domain!

  • Paste the Auth0 domain value in the following field so that you can use it in the next section to set up your API server:

The region subdomain (au, us, or eu) is optional. Some Auth0 Domains don't have it.

Set Up and Run the Lumen Project

Start by cloning the Lumen project and checking out the basic-authorization branch:

git clone https://github.com/auth0-developer-hub/api_lumen_php_hello-world.git --branch basic-authorization

Make the project directory your current working directory:

cd api_lumen_php_hello-world

Install the Lumen project dependencies:

composer install

Now, create a .env file under the project directory and populate it as follows:

.env
PORT=6060
CLIENT_ORIGIN_URL=http://localhost:4040
AUTH0_AUDIENCE=AUTH0-AUDIENCE
AUTH0_DOMAIN=AUTH0-DOMAIN

Execute the following command to run the Lumen API server:

php -S localhost:6060 -t public

Optional: Add Caching to Your Project

The Auth0 PHP SDK supports (and recommends) using a PSR-6 Compatible Caching Library to increase the performance of the authorization process. You can use that library to temporarily store the JWKS public keys. Adding this cache layer avoids making a request to the Auth0 well-known endpoint every time you need to verify an access token.

Follow these steps to add cache to this project.

Start by adding the symfony/cache dependency:

composer require symfony/cache

You need this dependency as it provides an adapter that wraps Lumen's cache as a PSR-6 compatible interface, which the Auth0 PHP SDK requires.

Set the cache driver on your .env file using a CACHE_DRIVER variable:

.env
PORT=6060
CLIENT_ORIGIN_URL=http://localhost:4040
AUTH0_AUDIENCE=AUTH0-AUDIENCE
AUTH0_DOMAIN=AUTH0-DOMAIN
CACHE_DRIVER=file

Lumen supports a wide variety of cache drivers. Please refer to the "Cache" Lumen document for more details.

Now, create a cache.php file under the config directory to configure your cache:

config/cache.php
<?php
return [
'default' => env('CACHE_DRIVER'),
'stores' => [
'file' => [
'driver' => 'file',
'path' => env('CACHE_PATH', storage_path('framework/cache')),
],
],
];

This cache configuration will vary depending on the driver that you choose to use.

Next, update the bootstrap/app.php file to make your cache config file available to Lumen:

bootstrap/app.php
<?php
//...
// Make the cache config file available for the application
$app->configure('cache');
//...

Finally, open the config/auth0.php file and add useCache to enable caching for Auth0:

config/auth0.php
<?php
return [
'domain' => env('AUTH0_DOMAIN'),
'audience' => [ env('AUTH0_AUDIENCE') ],
'useCache' => true // Add this line
];
//...

Make an Authenticated API Request

You can use a terminal application to make an authenticated request to your API server. An authenticated request is a request that includes a bearer token in its authorization header. That bearer token is the access token in JSON Web Token (JWT) format that you obtained earlier from the Auth0 Dashboard.

You can structure the authenticate request as follows:

curl --request GET \
--url http:/localhost:6060/api/messages/protected \
--header 'authorization: Bearer AUTH0-ACCESS-TOKEN'

Execute the command above on your terminal and ensure that you get the following response:

{
"text": "The API successfully validated your access token."
}

Request API Resources from a Client Application

Let's simulate an essential feature of an API: serving data to client applications.

You can pair this API server with a client application that matches the technology stack that you use at work. Any "Hello World" client application can communicate with this "Hello World" API server sample.

You can simulate a secure full-stack application system in no time. Each client application sample gives you clear instructions to get it up and running quickly.

Once set up, you can test the client-server connection in the http://localhost:4040/external-api page of your client application.

Pick a Single-Page Application (SPA) code sample in your preferred frontend framework and language: