Laravel API Authorization By Example: Using Auth0 Laravel SDK
Published on March 12, 2024This Laravel guide will help you learn how to secure a Laravel API application using token-based authorization. You'll learn how to integrate Auth0 by Okta with Laravel to implement the following security features:
- 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).
- Make authenticated requests to a secure Laravel API server.
- Create permissions, roles, and users in the Auth0 Dashboard.
- Perform Role-Based Access Control (RBAC) in Laravel.
How Does Auth0 Work?
With the help of Auth0 by Okta, you don't need to be an expert on identity protocols, such as OAuth 2.0 or OpenID Connect, to understand how to secure your web application stack.
You first integrate your client applications with Auth0. Your application will then redirect users to an Auth0 customizable login page when they need to log in. Once your users log in successfully, Auth0 redirects them to your client app, returning an access token. The client application can then use that access token to access protected resources in your Laravel API server.
Project Requirements
Ensure that you have the following tools installed in your system:
- PHP
8.2+
- Composer
v2.6+
- Docker Desktop
v4.20+
(Required only when using Laravel Sail environment)
Get the Starter Project
You have created a starter project to help you learn Laravel security concepts through hands-on practice. You can focus on writing the Laravel logic to secure your application.
Start by cloning the api_laravel_php_hello-world_laravel-sdk
repository on its starter
branch:
git clone -b starter [email protected]:auth0-developer-hub/api_laravel_php_hello-world_laravel-sdk.git
Once you clone the repo, make api_laravel_php_hello-world_laravel-sdk
your current directory:
cd api_laravel_php_hello-world_laravel-sdk
Install the Laravel project dependencies as follows:
composer install
The starter Laravel project defines the following API endpoints to let client applications access a simple message
resource:
# get a public messageGET /api/messages/public# get a protected messageGET /api/messages/protected# get an admin messageGET /api/messages/admin
The starter project does not implement access control for these endpoints. After you follow the steps in this guide, the API server will require each request to have a valid access token on their authorization header to access /api/messages/protected
and /api/messages/admin
. /api/messages/public
would be the only public endpoint. Later, you'll integrate this Laravel API with an actual client application using a frontend technology of your choice.
You'll run your Laravel server on port 6060
locally. The compatible demo client application runs on http://localhost:4040
by default. However, this Laravel starter application uses CORS to restrict which origins can request its resources.
You'll manage these configuration elements of your Laravel application using environment variables. As such, create a .env
file under the root project directory:
touch .env
Populate your .env
file with the following content:
APP_PORT=6060CLIENT_ORIGIN_URL=http://localhost:4040
The APP_PORT
environment variable defines the port in which your Laravel API server will run (when using Laravel Sail): http://localhost:6060
. The CLIENT_ORIGIN_URL
variable defines the origin from which a browser can load resources from your Laravel API — other than your API's origin.
Finally, open another terminal tab and execute this command to run your Laravel application:
php artisan serve --port 6060
If you're using Laravel Sail, use the following command to run the Laravel API server:
./vendor/bin/sail up -d
You are ready to start implementing authorization in this Laravel project. First, you'll need to configure the Larave API server to connect successfully to Auth0. Afterward, you'll use the auth0-php
package to validate bearer tokens from incoming API requests.
Configure Laravel with Auth0
Follow these steps to get started with the Auth0 Identity Platform quickly:
Sign up and create an Auth0 Application
A free account also offers you:
- Auth0 Universal Login for Web, iOS & Android.
- Up to 2 social identity providers like Google, GitHub, and Twitter.
- Up to 3 Actions, Rules, & Hooks to customize and extend Auth0's capabilities.
During the sign-up process, you create something called an Auth0 Tenant, representing the product or service to which you are adding authentication.
Once you sign in, Auth0 takes you to the Dashboard. Open the "APIs" section of the Auth0 Dashboard.
Then, click the "Create API" button. A modal opens with a form to provide a name for the API registration and define an API Identifier. Use the following values:
Hello World API Server
https://hello-world.example.com
Click the "Create" button to complete the process. Your Auth0 API registration page loads up.
A page loads up, presenting all the details about your application register with Auth0.
Next, locate the "General Settings" section.
Store the "Identifier" value in the following field to set up your Laravel API server in the next section:
In the next step, you'll learn how to help Laravel and Auth0 communicate.
What's the relationship between Auth0 Tenants and Auth0 Applications?
Let's say that you have a photo-sharing app called "Laragram". You then would create an Auth0 tenant called laragram
. From a customer perspective, Laragram is that customer's product or service.
Now, say that Laragram is available on three platforms: web as a single-page application and Android and iOS as a native mobile application. If each platform needs authentication, you need to create three Auth0 applications to provide the product with everything it needs to authenticate users through that platform.
Laragram users belong to the Auth0 Laragram tenant, which shares them across its Auth0 applications.
Install the Auth0 Laravel SDK
You will install the Auth0 Laravel SDK. With this SDK, you will be able to communicate with Auth0 and validate the Auth0 JWT access token received in the API requests:
composer require auth0/login:^7.9 --update-with-all-dependencies
You also need to publish the configuration file of the Auth0 Laravel SDK using the following command:
php artisan vendor:publish --tag auth0
The above command will publish the Auth0 Laravel SDK configurations to the file config/auth0.php
.
The Auth0 Laravel SDK supports authentication routes by default, but the Laravel API server doesn't need authentication routes as it will only support the use of JWT token for authorizing the incoming requests. Let's disable this behavior by setting the registerAuthenticationRoutes
config to false
in the config/auth0.php
config file:
<?phpdeclare(strict_types=1);use Auth0\Laravel\Configuration;use Auth0\SDK\Configuration\SdkConfiguration;return Configuration::VERSION_2 + ['registerGuards' => true,'registerMiddleware' => true,'registerAuthenticationRoutes' => false,'configurationPath' => null,'guards' => ['default' => [Configuration::CONFIG_STRATEGY => Configuration::get(Configuration::CONFIG_STRATEGY, SdkConfiguration::STRATEGY_NONE),Configuration::CONFIG_DOMAIN => Configuration::get(Configuration::CONFIG_DOMAIN),Configuration::CONFIG_CUSTOM_DOMAIN => Configuration::get(Configuration::CONFIG_CUSTOM_DOMAIN),Configuration::CONFIG_CLIENT_ID => Configuration::get(Configuration::CONFIG_CLIENT_ID),Configuration::CONFIG_CLIENT_SECRET => Configuration::get(Configuration::CONFIG_CLIENT_SECRET),Configuration::CONFIG_AUDIENCE => Configuration::get(Configuration::CONFIG_AUDIENCE),Configuration::CONFIG_ORGANIZATION => Configuration::get(Configuration::CONFIG_ORGANIZATION),Configuration::CONFIG_USE_PKCE => Configuration::get(Configuration::CONFIG_USE_PKCE),Configuration::CONFIG_SCOPE => Configuration::get(Configuration::CONFIG_SCOPE),Configuration::CONFIG_RESPONSE_MODE => Configuration::get(Configuration::CONFIG_RESPONSE_MODE),Configuration::CONFIG_RESPONSE_TYPE => Configuration::get(Configuration::CONFIG_RESPONSE_TYPE),Configuration::CONFIG_TOKEN_ALGORITHM => Configuration::get(Configuration::CONFIG_TOKEN_ALGORITHM),Configuration::CONFIG_TOKEN_JWKS_URI => Configuration::get(Configuration::CONFIG_TOKEN_JWKS_URI),Configuration::CONFIG_TOKEN_MAX_AGE => Configuration::get(Configuration::CONFIG_TOKEN_MAX_AGE),Configuration::CONFIG_TOKEN_LEEWAY => Configuration::get(Configuration::CONFIG_TOKEN_LEEWAY),Configuration::CONFIG_TOKEN_CACHE => Configuration::get(Configuration::CONFIG_TOKEN_CACHE),Configuration::CONFIG_TOKEN_CACHE_TTL => Configuration::get(Configuration::CONFIG_TOKEN_CACHE_TTL),Configuration::CONFIG_HTTP_MAX_RETRIES => Configuration::get(Configuration::CONFIG_HTTP_MAX_RETRIES),Configuration::CONFIG_HTTP_TELEMETRY => Configuration::get(Configuration::CONFIG_HTTP_TELEMETRY),Configuration::CONFIG_MANAGEMENT_TOKEN => Configuration::get(Configuration::CONFIG_MANAGEMENT_TOKEN),Configuration::CONFIG_MANAGEMENT_TOKEN_CACHE => Configuration::get(Configuration::CONFIG_MANAGEMENT_TOKEN_CACHE),Configuration::CONFIG_CLIENT_ASSERTION_SIGNING_KEY => Configuration::get(Configuration::CONFIG_CLIENT_ASSERTION_SIGNING_KEY),Configuration::CONFIG_CLIENT_ASSERTION_SIGNING_ALGORITHM => Configuration::get(Configuration::CONFIG_CLIENT_ASSERTION_SIGNING_ALGORITHM),Configuration::CONFIG_PUSHED_AUTHORIZATION_REQUEST => Configuration::get(Configuration::CONFIG_PUSHED_AUTHORIZATION_REQUEST),Configuration::CONFIG_BACKCHANNEL_LOGOUT_CACHE => Configuration::get(Configuration::CONFIG_BACKCHANNEL_LOGOUT_CACHE),Configuration::CONFIG_BACKCHANNEL_LOGOUT_EXPIRES => Configuration::get(Configuration::CONFIG_BACKCHANNEL_LOGOUT_EXPIRES),],'api' => [Configuration::CONFIG_STRATEGY => SdkConfiguration::STRATEGY_API,],'web' => [Configuration::CONFIG_STRATEGY => SdkConfiguration::STRATEGY_REGULAR,Configuration::CONFIG_COOKIE_SECRET => Configuration::get(Configuration::CONFIG_COOKIE_SECRET, env('APP_KEY')),Configuration::CONFIG_REDIRECT_URI => Configuration::get(Configuration::CONFIG_REDIRECT_URI, env('APP_URL') . '/callback'),Configuration::CONFIG_SESSION_STORAGE => Configuration::get(Configuration::CONFIG_SESSION_STORAGE),Configuration::CONFIG_SESSION_STORAGE_ID => Configuration::get(Configuration::CONFIG_SESSION_STORAGE_ID),Configuration::CONFIG_TRANSIENT_STORAGE => Configuration::get(Configuration::CONFIG_TRANSIENT_STORAGE),Configuration::CONFIG_TRANSIENT_STORAGE_ID => Configuration::get(Configuration::CONFIG_TRANSIENT_STORAGE_ID),],],'routes' => [Configuration::CONFIG_ROUTE_INDEX => Configuration::get(Configuration::CONFIG_ROUTE_INDEX, '/'),Configuration::CONFIG_ROUTE_CALLBACK => Configuration::get(Configuration::CONFIG_ROUTE_CALLBACK, '/callback'),Configuration::CONFIG_ROUTE_LOGIN => Configuration::get(Configuration::CONFIG_ROUTE_LOGIN, '/login'),Configuration::CONFIG_ROUTE_AFTER_LOGIN => Configuration::get(Configuration::CONFIG_ROUTE_AFTER_LOGIN, '/'),Configuration::CONFIG_ROUTE_LOGOUT => Configuration::get(Configuration::CONFIG_ROUTE_LOGOUT, '/logout'),Configuration::CONFIG_ROUTE_AFTER_LOGOUT => Configuration::get(Configuration::CONFIG_ROUTE_AFTER_LOGOUT, '/'),],];
Create a communication bridge between Laravel and Auth0
In this guide, you'll implement token-based authorization. That is, your Laravel API server will protect an endpoint by requiring that each request to that endpoint contains a valid access token.
The issuer of those access tokens will be an Auth0 authorization server. Your Laravel API server needs to validate the access token coming along with each request, i.e., verify it was issued by Auth0, it is not expired, your API is the intended receiver, among other things.
You'll need the Auth0 Domain and Auth0 Audience values to validate the access tokens.
When setting up APIs in the Auth0 Dashboard, you also refer to the API identifier as the Audience value, which you have already set up in the previous 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:
region
subdomain (au
, us
, or eu
) is optional. Some Auth0 Domains don't have it.Get an Auth0 access token
You'll also need a test access token to practice making secure calls to your API from a terminal application.
You can get a test access token from the Auth0 Dashboard by following these steps:
- Head back to the Auth0 registration page of your Laravel API and click on the "Test" tab.
-
Locate the section called "Response" and click on the copy button in 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.
Define the Auth0 Environment Variables
Update the .env
file under the project directory as follows to integrate the Auth0 Domain and Auth0 Audience values with your Laravel application:
APP_PORT=6060CLIENT_ORIGIN_URL=http://localhost:4040AUTH0_AUDIENCE=AUTH0-AUDIENCEAUTH0_DOMAIN=AUTH0-DOMAIN
Restart your development server for your Laravel project to become aware of these .env
file changes:
php artisan serve --port 6060
Or if you're using Laravel Sail:
./vendor/bin/sail restart
That's all the configurations you need to do for the SDK to work. Once you reach the "Request Laravel API Resources From a Client App" section of this guide, you'll learn how to use CLIENT_ORIGIN_URL
along with an Auth0 Audience value to request protected resources from your Laravel API using a client application that is also protected by Auth0.
Protect Laravel API Endpoints
Now that you have the Auth0 Laravel SDK configured and ready to use, it's time to protect the endpoints. Let's update the API routes file to make use of the SDK authentication guard middleware. Update the routes/api.php
file with the following code:
<?phpuse App\Http\Controllers\MessagesController;use Illuminate\Support\Facades\Auth;use Illuminate\Support\Facades\Route;/*|--------------------------------------------------------------------------| API Routes|--------------------------------------------------------------------------|| Here is where you can register API routes for your application. These| routes are loaded by the RouteServiceProvider and all of them will| be assigned to the "api" middleware group. Make something great!|*/Auth::shouldUse('auth0-api');Route::group(['prefix' => 'messages'], function ($router) {Route::get('public', [MessagesController::class, 'showPublicMessage']);Route::group(['middleware' => 'auth'], function () {Route::get('protected', [MessagesController::class, 'showProtectedMessage']);Route::get('admin', [MessagesController::class, 'showAdminMessage']);});});
You call Auth::shouldUse('auth0-api')
before the API routes to instruct the Laravel Auth service to use the Auth0 Laravel SDK authentication guard instead of the default one. These endpoints should be protected now and require authentication to access them.
Handle Authentication Exception
Laravel's default behavior when there's an authentication exception is to redirect to a login page if the request is coming from the web. Since the app is a Laravel API, let's ensure it consistently returns the correct authentication error response when the authentication fails. Update the Authenticate
middleware with the following code:
<?phpnamespace App\Http\Middleware;use App\Exceptions\ApiException;use Illuminate\Auth\Middleware\Authenticate as Middleware;use Illuminate\Http\Request;class Authenticate extends Middleware{/*** Get the path the user should be redirected to when they are not authenticated.*/protected function redirectTo(Request $request): ?string{if ($this->auth->guard()->guest())throw new ApiException('Requires authentication', 401);return null;}}
With this update, the app will now always return an appropriate authentication error response instead of trying to redirect the user to a login page.
Test Your Protected API Endpoints
Use an application like Postman or a terminal to test that your API server is working as prescribed.
As an anonymous user:
Request:
curl localhost:6060/api/messages/public
Response:
Status code: 200
{"text": "This is a public message."}
Request:
curl localhost:6060/api/messages/protected
Response:
Status code: 401
{"message": "Requires authentication"}
Request:
curl localhost:6060/api/messages/admin
Response:
Status code: 401
{"message": "Requires authentication"}
Request:
curl localhost:6060/api/messages/invalid
Response:
Status code: 404
{"message": "Not Found"}
For any other error, the response will be as follows:
Response:
Status code: 500
{"message": "Internal Server Error"}
As a user with a valid test access token:
In the "Configure Laravel with Auth0" section, you learned how to get a test access token. Use that access token in this section, please.
Make a secure request to your API server by including an access token in the authorization header:
Request:
curl --request GET \--url http:/localhost:6060/api/messages/protected \--header 'authorization: Bearer AUTH0-ACCESS-TOKEN'
Response:
Status code: 200
{"text": "This is a protected message."}
Request:
curl --request GET \--url http:/localhost:6060/api/messages/admin \--header 'authorization: Bearer AUTH0-ACCESS-TOKEN'
Response:
Status code: 200
{"text": "This is an admin message."}
Request:
curl --request GET \--url http:/localhost:6060/api/messages/invalid \--header 'authorization: Bearer AUTH0-ACCESS-TOKEN'
Response:
Status code: 404
{"message": "Not Found"}
Any other errors as needed if no other status codes apply:
Response:
Status code: 500
{"message": "Internal server error"}
When using an invalid test access token:
Request:
curl --request GET \--url http:/localhost:6060/api/messages/protected \--header 'authorization: Bearer invalidtoken1234567890'
Response:
Status code: 401
{"message": "Requires authentication"}
Request Laravel API Resources From a Client App
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 quickly get it up and running.
Once set up, you can test the client-server connection in the http://localhost:4040/protected
or http://localhost:4040/admin
pages of your client application.
Pick a Single-Page Application (SPA) code sample in your preferred frontend framework and language:
That's all it takes to integrate a client application with a Laravel API server that is also secured by Auth0 and to use an access token to consume protected server resources from the client application.
Set Up Role-Based Access Control (RBAC)
Within the context of Auth0, Role-based access control (RBAC) systems assign permissions to users based on their role within an organization. Everyone who holds that role has the same set of access rights. Those who hold different roles have different access rights.
Developers who use Role-based access control (RBAC) for access management can mitigate the errors that come from assigning permissions to users individually.
You can use the Auth0 Dashboard to enable Role-Based Access Control (RBAC) in any API that you have already registered with Auth0. You then implement RBAC by creating API permissions, assigning those permissions to a role, and assigning that role to any of your users.
Whenever a user logs in to one of your client applications, the Auth0 authorization server issues an access token that the client can use to make authenticated requests to an API server. Auth0 authorization servers issue access tokens in JSON Web Token (JWT) format.
When you enable Auth0 Role-Based Access Control (RBAC) for an API, the access token will include a permissions
claim that has all the permissions associated with any roles that you have assigned to that user.
For this particular API code sample, the access token present in the authorization header of a request must include a permissions
claim that contains the read:admin-messages
permission to access the GET /api/messages/admin
endpoint.
Enable Role-Based Access Control (RBAC)
-
Open the APIs section of the Auth0 Dashboard and select your "Hello World API Server" registration.
-
Click on the "Settings" tab and locate the "RBAC Settings" section.
-
Switch on the "Enable RBAC" and "Add Permissions in the Access Token" options.
Create an API permission
In the same Auth0 API registration page, follow these steps:
- Click on the "Permissions" tab and fill a field from the "Add a Permission (Scope)" section with the following information:
read:admin-messages
Read admin messages
- Click the "+ Add" button to store the permission.
Create a role with permissions
Create a role
-
Open the User Management > Roles section of the Auth0 Dashboard.
-
Click on the Create role button and fill out the "New Role" form with the following values:
messages-admin
Access admin messaging features
- Click on the Create button.
Add permissions to the role
-
Click on the "Permissions" tab of the roles page.
-
Click on the "Add Permissions" button.
-
Select the "Hello World API Server" from the dropdown menu that comes up and click the "Add Permissions" button.
-
Select all the permissions available by clicking on them one by one or by using the "All" link.
-
Finally, click on the "Add Permissions" button to finish up.
Create an admin user
-
Open the User Management > Users section from the Auth0 Dashboard.
-
Click on the "Create user" button and fill out the form with the required information. Alternatively, you can also click on any of your existing users to give one of them the admin role.
-
On the user's page, click on the "Roles" tab and then click on the "Assign Roles" button.
-
Select the
messages-admin
role from the dropdown menu and click on the "Assign" button.
Implement RBAC in a Laravel API
Now that you have created the permission read:admin-messages
in the Auth0 API application, let's use it in the Laravel API to protect the /api/messages/admin
endpoint. You will only show the admin message to users who have this permission.
For convenience, the Auth0 Laravel SDK supports the Laravel authorization middleware can
. You can simply use it in the messages/admin
route as in the following:
<?phpuse App\Http\Controllers\MessagesController;use Illuminate\Support\Facades\Auth;use Illuminate\Support\Facades\Route;/*|--------------------------------------------------------------------------| API Routes|--------------------------------------------------------------------------|| Here is where you can register API routes for your application. These| routes are loaded by the RouteServiceProvider and all of them will| be assigned to the "api" middleware group. Make something great!|*/Auth::shouldUse('auth0-api');Route::group(['prefix' => 'messages'], function ($router) {Route::get('public', [MessagesController::class, 'showPublicMessage']);Route::group(['middleware' => 'auth'], function () {Route::get('protected', [MessagesController::class, 'showProtectedMessage']);Route::get('admin', [MessagesController::class, 'showAdminMessage'])->can('read:admin-messages');});});
Finally, let's add an exception handler method for when the user has insufficient permissions to access the admin message resource. Update the app/Exceptions/Handler.php
file with the following code:
<?phpnamespace App\Exceptions;use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;use Illuminate\Http\JsonResponse;use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;use Throwable;class Handler extends ExceptionHandler{/*** The list of the inputs that are never flashed to the session on validation exceptions.** @var array<int, string>*/protected $dontFlash = ['current_password','password','password_confirmation',];/*** Register the exception handling callbacks for the application.*/public function register(): void{$this->renderable(function (NotFoundHttpException $e) {return $this->apiError('Not Found', 404);});$this->renderable(function (MethodNotAllowedHttpException $e) {return $this->apiError('Not Allowed Http Method', 405);});$this->renderable(function (AccessDeniedHttpException $e) {return $this->apiError('Insufficient permissions to access resource', 403);});$this->renderable(function (ApiException $e) {return $this->apiError($e->getMessage(), $e->getCode());});$this->reportable(function (Throwable $e) {return $this->apiError('Internal Server Error', 500);});}protected function apiError($message, $code): JsonResponse{return response()->json(['message' => $message], $code);}}
Access the Admin Endpoint
Let's test access to the GET /api/messages/admin
endpoint by simulating a real user login and requesting that protected resource using a real access token.
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.
When you log in to a "Hello World" client application as a user who has the messages-admin
role, your access token will have the required permissions to access the GET /api/messages/admin
endpoint.
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:
Once you set up the client application, log in and visit the guarded "Admin" page (http://localhost:4040/admin
).
When you log in to a "Hello World" client application as a user who has the messages-admin
role, your access token will have the required permissions to access the GET /api/messages/admin
endpoint, and you'll get the following response:
{"text": "This is an admin message."}
However, when you log in as a user who doesn't have the messages-admin
role, you'll get a 403 Forbidden
status code and the following response:
{"message": "Permission denied"}
Next Steps
You have implemented token-based authorization in Laravel to restrict access to server resources.
This guide covered the most common authorization use case for a Laravel API: use middleware to validate access tokens and make authenticated requests to your API. However, Auth0 is an extensible and flexible identity platform that can help you achieve even more. If you have a more complex use case, check out the Auth0 Architecture Scenarios to learn more about the typical architecture scenarios you have identified when working with customers on implementing Auth0.
We'll cover advanced authorization strategies in future guides, such as implementing Fine-Grained Authorization (FGA).