Basic authentication using Laravel middleware

  • avatar
  • 1.2K Views
  • 4 Likes
  • 4 mins read

Laravel, the PHP framework renowned for its simplicity and elegance, continues to be a top choice for developers worldwide. Among its many features, Laravel offers robust middleware functionality, allowing for seamless integration of authentication mechanisms. In this article, we'll explore the implementation of basic authentication using middleware in Laravel, investigating its benefits and practical applications.

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.

What is a Laravel middleware

At the core of Laravel's middleware lies its ability to intercept HTTP requests and responses. This interception enables developers to perform various tasks, including authentication, before the request reaches the intended route. By using middleware, Laravel offers a flexible and efficient way to enforce authentication requirements across different parts of an application.

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.

Basic authentication implemention in Laravel

Implementing basic authentication with middleware in Laravel involves creating a middleware class that verifies the user's credentials before allowing access to protected routes. Run the following command in your Laravel project directory to generate the middleware:

php artisan make:middleware BasicAuthentication

This command will create a new middleware file named BasicAuthentication in the app/Http/Middleware directory.

Within this middleware, developers can define the logic for authenticating users, such as checking credentials against a database or other authentication providers. For illustrative purposes, we've hardcoded the username and password in constants, a practice that should be avoided at all costs.

<?php

namespace App\\Http\\Middleware;

use Closure;
use Illuminate\\Http\\Request;
use Illuminate\\Http\\Response;
use Symfony\\Component\\HttpKernel\\Exception\\HttpException;

class BasicAuthentication
{
private const USER= 'admin';
private const PASS= 'adminx';

public function handle(Request $request, Closure $next)
{
if ($request->hasHeader('Authorization') === false) {
// Display login prompt
header('WWW-Authenticate: Basic realm="HiBit"');
exit;
}

$credentials = base64_decode(substr($request->header('Authorization'), 6));
list($username, $password) = explode(':', $credentials);

if ($username !== self::USER || $password !== self::PASS) {
// Provided username or password does not match, throw an exception
// Alternatively, the login prompt can be displayed once more
throw new HttpException(Response::HTTP_UNAUTHORIZED);
}

return $next($request);
}
}

Open the app/Http/Kernel.php file and register the middleware adding it to the $middlewareAliases array:

protected $middlewareAliases = [
...

'basic.authentication => \\App\\Http\\Middleware\\BasicAuthentication::class,
];

Apply the authentication middleware to the routes that require authentication:

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

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

Conclusion

Exploring Laravel's basic authentication via middleware provides developers with a powerful and flexible solution for securing web applications. By leveraging middleware, developers can enforce authentication requirements with ease, ensuring consistent security across different parts of the application.

 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.