Laravel: How to Extract Auth Token from Request Headers

Updated: January 18, 2024 By: Guest Contributor Post a comment

Introduction

When building a web application with Laravel, handling authentication is a crucial part of the process. One common approach is to use tokens to authenticate users, which are typically passed along in the request headers. In this tutorial, we’ll go through how to extract an authentication token from request headers using Laravel’s powerful request class, middleware, and authentication features. This technique is particularly relevant when dealing with RESTful APIs and Single Page Applications (SPAs) where token-based authentication is standard practice.

Understanding the Request Object

The Laravel request object provides an object-oriented way of interacting with the HTTP request received by the server. This includes the ability to retrieve headers, query string parameters, POST data, and more. Firstly, it is important to understand how to access the request object within your Laravel application.

// Accessing request in a controller method
public function myControllerMethod(
    \Illuminate\Http\Request $request)
{
    $token = $request->header('Authorization');
}

Creating a Middleware for Token Extraction

Middlewares are a powerful feature in Laravel that allow you to filter HTTP requests entering your application. We can create a custom middleware to handle the extraction of an auth token from the request headers.

php artisan make:middleware TokenExtractionMiddleware

After creating the middleware, you’ll need to define the logic for extracting the token inside the handle() method in the newly created TokenExtractionMiddleware.php file.

namespace App\Http\Middleware;

use Closure;

class TokenExtractionMiddleware
{
    public function handle($request, Closure $next)
    {
        $token = $request->bearerToken();
        if (!$token) {
            // Handle the case where token is absent
            return response('Unauthorized', 401);
        }
        // You can attach the token to the request object
        $request->request->add(['access_token' => $token]);

        return $next($request);
    }
}

Now, after creating the middleware, you need to register it in your kernel.php to make sure that it is applied to the requests.

// Within your Kernel.php's $routeMiddleware array
'extract.token' => \App\Http\Middleware\TokenExtractionMiddleware::class,

You can now use this middleware either in your routes or controllers where you need token extraction.

// Assigning middleware to routes
Route::get('/api/user', function () {
    // Your secured resource access here
})->middleware('extract.token');

Working with Authenticated Routes

If the purpose of extracting the token is to authenticate users, you can make use of Laravel’s authentication guard system. When using API tokens, many developers opt for the auth:api guard that ships with Laravel. By attaching this middleware to your routes, Laravel will extract and validate the token for you.

// This route will require a valid token
to access the authenticated user details
Route::middleware('auth:api')->get('/user', function (
    \Illuminate\Http\Request $request)
{
    return $request->user();
});

Creating Tokens with Laravel Sanctum

Laravel Sanctum is a simple package for API token authentication that is perfect for SPAs and simple APIs. When you have Sanctum installed and configured, creating tokens is straightforward.

$user = \App\Models\User::find(1);
$token = $user->createToken('Token Name')->plainTextToken;

Sending tokens from the client to your Laravel app would typically be done using the Authorization header.

// Example Authorization header
Authorization: Bearer 1|abcdefghijklnopqrstuvwxyzABCDEFG

Error Handling and Security Considerations

When you extract tokens from request headers, ensure to implement appropriate error handling. Token validity should always be checked, and clear responses should be sent back when there is an issue with the token. Always remember to secure your API using HTTPS to protect the tokens from being compromised during transmission.

Conclusion

In conclusion, extracting an auth token from the request headers in Laravel can be handled in several ways. Whether it’s within a controller method, using middleware, or by utilizing built-in authentication guards, Laravel offers tools tailored for the task. Remember to follow best practices regarding security and proper management of API tokens, especially when it comes to their scope and lifespan. By now, you should have a complete understanding of how to extract and work with auth tokens in your Laravel applications. Happy coding!