JWT authentication using Laravel middleware

  • avatar
  • 6.4K Views
  • 1 Like
  • 6 mins read

Security is crucial in web development, and one widely used method for securing APIs and web applications is JSON Web Token (JWT) authentication. Laravel, a powerful PHP framework, offers robust support for JWT authentication, making it a popular choice among developers. In this guide, we'll explore the intricacies of JWT authentication in Laravel, from grasping the basics of JWT to implementing token decoding within Laravel middleware.

Prerequisites

Before exploring the implementation in the application, it's essential to understand authentication and authorization basics. Authentication verifies users' identities, while authorization controls their system access. Familiarity with authentication methods is key, check out the article popular authentication methods for Applications for more insights.

Understanding JSON Web Tokens

JSON Web Tokens (JWT) are compact, URL-safe tokens used for securely transmitting information between parties as JSON objects. Consisting of three parts - header, payload, and signature - JWTs contain metadata, claims, and a signature to ensure integrity and authenticity. Common claims include issuer, subject, and expiration time. Understanding these components is key to implementing JWT authentication effectively.

As an example, here is a JWT token:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

This JWT token comprises three sections separated by dots:

  1. Header: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

  2. Payload: eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ

  3. Signature: SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Each section is base64 URL encoded, and together they form a complete JWT token. Understanding the structure and content of a JWT token is essential for working with JWT authentication effectively.

What is a Laravel middleware

Middleware acts as a mediator between HTTP requests and responses in Laravel, offering a convenient way to filter incoming requests. It serves various purposes, including authentication, before the request reaches the intended route. In JWT authentication, middleware plays a pivotal role by intercepting requests, decoding JWT tokens, and validating user identity before granting access to protected routes.

Laravel's middleware stack allows for flexible authentication strategies tailored to the specific requirements of an application. Developers can leverage middleware groups to apply different authentication middleware to different parts of the application, allowing for fine-grained control over access to resources. Whether implementing session-based authentication, token-based authentication, or custom authentication methods, Laravel's middleware provides the flexibility to adapt to diverse authentication needs.

JSON Web Tokens implemention in Laravel

To decode JWT tokens and enable JWT authentication in your application, developers can opt to install a JWT package, which can significantly streamline development and reduce implementation time. Follow these steps to install the package:

  1. Open a terminal and navigate to your Laravel project directory.

  2. Use Composer to install the package by running the following command:

composer require firebase/php-jwt

Note: we've selected the Firebase package, but any alternative package is also applicable.

Once the installation process is complete, proceed to configure the package as per your application's requirements. Following configuration, developers can craft custom middleware responsible for decoding and validating JWT tokens. This middleware class ensures the authentication of users' credentials before granting access to protected routes. Run the following command in your Laravel project directory to generate the middleware:

php artisan make:middleware JsonWebTokenAuthentication

This command will create a new middleware file named JsonWebTokenAuthentication in the app/Http/Middleware directory. The following snippet demonstrates how JWT decoding can be implemented within Laravel middleware:

<?php

namespace App\\Http\\Middleware;

use Closure;
use Illuminate\\Http\\Request;
use Firebase\\JWT\\JWT;
use Firebase\\JWT\\SignatureInvalidException;
use Firebase\\JWT\\BeforeValidException;
use Firebase\\JWT\\ExpiredException;
use DomainException;
use InvalidArgumentException;
use UnexpectedValueException;

class JsonWebTokenAuthentication
{
public function handle(Request $request, Closure $next)
{
$bearerToken = $request->bearerToken() ?? '';
$key = config('PATH_TO_YOUR_KEY');

try {
$decoded = JWT::decode($bearerToken, $key);
} catch (InvalidArgumentException $e) {
// provided key/key-array is empty or malformed.
} catch (DomainException $e) {
// provided algorithm is unsupported OR
// provided key is invalid OR
// unknown error thrown in openSSL or libsodium OR
// libsodium is required but not available.
} catch (SignatureInvalidException $e) {
// provided JWT signature verification failed.
} catch (BeforeValidException $e) {
// provided JWT is trying to be used before "nbf" claim OR
// provided JWT is trying to be used before "iat" claim.
} catch (ExpiredException $e) {
// provided JWT is trying to be used after "exp" claim.
} catch (UnexpectedValueException $e) {
// provided JWT is malformed OR
// provided JWT is missing an algorithm / using an unsupported algorithm OR
// provided JWT algorithm does not match provided key OR
// provided key ID in key/key-array is empty or invalid.
}

return $next($request);
}
}

In the handle method of the AuthenticateJWT middleware, the JWT token is parsed and authenticated using the jwt-auth package. Additionally, custom validations can be implemented within the middleware to inspect further details of the token. These validations may include verifying the token issuer, checking the token's expiration time, or examining specific claims. If any of these custom validations fail, the middleware can return an unauthorized error response, ensuring that only authenticated users with valid tokens gain access to protected routes.

To integrate the AuthenticateJWT middleware into your Laravel application, navigate to the app/Http/Kernel.php file and register the middleware adding it to the $middlewareAliases array:

protected $middlewareAliases = [
...

'jwt.authentication => \\App\\Http\\Middleware\\JsonWebTokenAuthentication::class,
];

Apply the authentication middleware to the routes that require authentication:

Route::middleware(['jwt.authentication'])->group(function () {
// Protected routes
});

Once authenticated, the middleware proceeds to execute the requested route handler, granting access to the protected resource.

Conclusion

JWT authentication provides a robust and efficient method for securing APIs and web applications. Developers can explore resources like jwt.io for comprehensive documentation on JWTs and various available libraries for implementing JWT authentication. Whether using Laravel or any other framework, the principles of JWT authentication remain consistent, allowing developers to ensure secure transmission of data and validate user credentials effectively. By grasping the structure of JWT tokens and customizing middleware to handle authentication, developers can build secure and reliable web applications across various platforms and frameworks. With JWT authentication, the authentication process becomes streamlined, offering flexibility and scalability to meet the diverse security needs of modern web applications.

 Join Our Monthly Newsletter

Get the latest news and popular articles to your inbox every month

We never send SPAM nor unsolicited emails

0 Comments

Leave a Reply

Your email address will not be published.

Replying to the message: View original

Hey visitor! Unlock access to featured articles, remove ads and much more - it's free.