Basic Authentication in Laravel 9 Using Middleware

This Laravel 9 tutorial help to add basic authentication using laravel middleware. We will create a middleware class in Laravel 9 that authenticates the user using basicauth, After successfully authenticating user, Laravel will process the next request.

We will use middleware to provide the authentication for the REST call. This middleware will authorize the user at every request before the access data. The authentication configuration file is located at config/auth.php.

I will use the following files for this Laravel tutorial,

  • app/Http/Middleware/AuthMiddleware.php : This file is a middleware file that will handle middleware requests.
  • app/Helpers/Helper.php : This file is used to create an application common method.
  • app/Http/routes.php : This file will have routes of rest call.

Whats’s Basic Authentication

Basic authentication is a simple authentication process that is built on HTTP protocol. The client sends HTTP Requests with the user credentials that generate the Authorization header parameter.The Authorization header contains the base64-encoded string using username:password. The header params look like below:
Authorization: Basic HtsasCFskzByZA==

Where :
Authorization: This is the key name.
Basic HtsasCFskzByZA== : This is base64-encoded string value of passed credential.

You can also check other recommended tutorials of Lumen/Laravel,

We will add middleware in routes.php file.

$router->group(['prefix' => 'api/v1', 'middleware' => ['auth']], function($router)
   $router->POST('get_emaployee', 'EmployeeController@getEmployee');

Created routes group 'api/v1' using group method, passed the middleware params with middleware class name ‘auth’, We will create AuthMiddleware later on in this tutorial.

Created POST type HTTP request under 'api/v1' group, now the request url would be 'api/v1/get_employee', so whenever user will access this end points they will authenticate using auth middle-ware and then able to access employee data otherwise get error with HTTP response status code 401.

Now, We will create file AuthMiddleware.php into app/HTTP/Middleware/ folder, which will handle pre-flight requests.

helper = $helper;
     * Handle an incoming request.
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
    public function handle($request, Closure $next)
      $isAdmin = false;
      $user = $request->getUser();
      $pass = $request->getPassword();
      if(isset($user) && empty($user)) {
         return Helper::jsonpError("Username and password is wrong", 401, 401);
      if(isset($pass) && empty($pass)) {
         return Helper::jsonpError("Username and password is wrong", 401, 401);
      $isAdmin = $this->helper->AuthenticateUser(array("user" => $user, "pass" => $pass));
         $response = Helper::jsonpError("Not Authorized", 401, 401);
         return $response;
        return $next($request);

I am using HTTP Rest request to validate user and send response, You can also use local database table using model class. I will create a method into auth Helper.php file,

public function AuthenticateUser($cred) {
                  $base64 = base64_encode($cred['user'].":".$cred['pass']);
      $client = new Client([
          'base_uri' => 'http://auth-restpi-hostname',
          'timeout' => 300,
        'headers' => ['Content-Type' => 'application/json', "Accept" => "application/json", 'Authorization' => "Basic " . $base64],
          'http_errors' => false,
          'verify' => false
      $client = $this->_client($this->praxisAPI, $cred);
      try {
          $response = $client->get("/user");
          $data = json_decode($response->getBody()->getContents(), true);
          $status = $response->getStatusCode();
          if($status == 200) {
               return true;
         return false;
        } catch (\Exception $ex) { 
          return Helper::jsonpError("Auth - Unable to get user account details", 400, 400);

Now open http://localhost/api/v1/get_emaployee using browser.

You will get 401 “Unauthorized” response for those requests which missed or passed incorrect credentials, You will get a 200 Status code with employee data on success of basic auth middleware.

One thought on “Basic Authentication in Laravel 9 Using Middleware

Leave a Reply

Your email address will not be published.