Basic Authentication in Laravel 5 Using Middleware

This Laravel 5 tutorial help to add basic authentication using laravel middleware. We will create a middleware class in Laravel 5 that authenticate user using basicauth, After successful authenticating user, Laravel will process next request.We will use a 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 following files for this Laravel tutorial,

  • app/Http/Middleware/AuthMiddleware.php : This file is middleware file which will handle middleware request.
  • app/Helpers/Helper.php : This file is use to create 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 which are built on HTTP protocol. The client sends HTTP Requests with the user credentials that generate 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.

Created routes group 'api/v1' using group method,passed the middleware params with middleware class name 'auth', We will create AuthMiddleware later on 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, that will handle pre-flight 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 method into auth Helper.php file,

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 200 Status code with employee data on success of basic auth middleware.

One thought on “Basic Authentication in Laravel 5 Using Middleware

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.