laravel logo
php logo

Laravel/PHP API: Authorization Code Sample

v8
Published on November 19, 2021

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

  • Register a Laravel API in the Auth0 Dashboard.

  • Use Laravel middleware to enforce API security policies.

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

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

  • Make authenticated requests to a secure Laravel API server.

Code Sample Specs

This code sample uses the following main tooling versions:

  • Laravel v8.75.0
  • PHP v7.4 or v8.0
  • Auth0 PHP SDK v8.0.3

The Laravel 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 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.

Get an Auth0 access token

If you are using this API with any of the compatible Hello World client applications, you can skip this section. Your client application will get an access token from Auth0 and use it to make authenticated requests to your API.

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 configuration 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.

Set Up and Run the Laravel Project

Start by cloning the Laravel project:

COMMAND
git clone https://github.com/auth0-developer-hub/api_laravel_php_hello-world.git

Make the project directory your current working directory:

COMMAND
cd api_laravel_php_hello-world

Then, check out the basic-authorization branch, which holds all the code related to implementing token-based authorization to protect resources in a Laravel API:

COMMAND
git checkout basic-authorization

If you are running your project with Sail, generate a Laravel app key value using the following command:

COMMAND
./vendor/bin/sail artisan key:generate

If you are running your project with Composer, you can use the following command instead:

COMMAND
php artisan key:generate

Store the output from any of the commands above in the following field:

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

.env
APP_KEY=KEY-VALUE
SERVER_PORT=6060
CLIENT_ORIGIN_URL=http://localhost:4040
AUTH0_AUDIENCE=AUTH0-AUDIENCE
AUTH0_DOMAIN=AUTH0-DOMAIN

With your .env in place, install the Laravel project dependencies:

COMMAND
composer install

Execute the following command to run the Laravel API server using Sail:

COMMAND
./vendor/bin/sail up

Otherwise, use the following command to run the API server using Composer:

COMMAND
php artisan serve

Make an Authenticated API Request

If you are using this API with any of the compatible Hello World client applications, you can skip to the "Request API Resources from a Client Application" section. Your client application will make authenticated requests to your API.

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:

COMMAND
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": "This is a protected message."
}

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.

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

angular
typescript
Angular Standalone Components Code Sample:Basic Authentication
This code sample uses Angular Standalone Components with TypeScript to implement single-page application authentication using the Auth0 Angular SDK.
angular
typescript
Angular Code Sample:Basic Authentication
This code sample uses Angular with TypeScript to implement single-page application authentication using the Auth0 Angular SDK.
react
javascript
React Code Sample:Basic Authentication
JavaScript code that implements user login, logout and sign-up features to secure a React Single-Page Application (SPA) using Auth0.
react
javascript
React Router 6 Code Sample:Basic Authentication
Code sample showing how to protect a simple React single-page application using React Router 6, Auth0, and JavaScript.
react
typescript
React/TypeScript Code Sample:Basic Authentication
Code sample of a simple React single-page application built TypeScript that implements authentication using Auth0.
react
typescript
React Router 6/TypeScript Code Sample:Basic Authentication
Code sample showing how to protect a simple React single-page application using React Router 6, Auth0, and TypeScript.
svelte
javascript
Svelte Code Sample:Basic Authentication
JavaScript code that implements user login, logout and sign-up features to secure a Svelte Single-Page Application (SPA), using routing middleware.
vue
javascript
Vue.js 2 Code Sample:Basic Authentication
This code sample uses Vue.js 2 with JavaScript to implement single-page application authentication using the Auth0 SPA SDK.
vue
javascript
Vue.js Composition API Code Sample:Basic Authentication
This code sample uses Vue.js 3 with JavaScript and the Composition API to implement single-page application authentication using the Auth0 Vue SDK.
vue
javascript
Vue.js Options API Code Sample:Basic Authentication
This code sample uses Vue.js 3 with JavaScript and the Options API to implement single-page application authentication using the Auth0 Vue SDK.

Once you set up the client application, log in and visit the protected "Profile" page (http://localhost:4040/profile) to see all the user profile information that Auth0 securely shares with your application using ID tokens.

Then, visit the "Protected" page (http://localhost:4040/protected) or the "Admin" page (http://localhost:4040/admin) to practice requesting protected resources from an external API server using access tokens.