Implementing API-Based Authentication for Middleware Authorization in Laravel: A Step-by-Step Guide (2024)

In modern web development, APIs have become a ubiquitous tool for building scalable, reliable, and secure applications. Laravel, one of the most popular PHP frameworks, provides a powerful set of tools for working with APIs, including middleware authorization. In this tutorial, we’ll show you how to implement API-based authentication in Laravel to provide secure access to your application’s resources.

Implementing API-Based Authentication for Middleware Authorization in Laravel: A Step-by-Step Guide (1)

Step 1: Setting Up the Laravel Application

First, we’ll set up a basic Laravel application with the necessary dependencies. We’ll create a new Laravel project using the Composer command-line tool and install the Laravel Passport package for API authentication.

To get started, we’ll create a new Laravel project using Composer. If you don’t have Composer installed, you can download it from https://getcomposer.org/.

Open a terminal or command prompt and navigate to the directory where you want to create your project. Then, run the following command:

composer create-project --prefer-dist laravel/laravel your-project-name

This will create a new Laravel project with the name “your-project-name” and install all the necessary dependencies.

Next, we’ll install the Laravel Passport package for API authentication. Laravel Passport provides a set of APIs for managing OAuth2 tokens, which we’ll use to authenticate users in our application.

To install Laravel Passport, run the following command in your project directory:

composer require laravel/passport

This will install the Laravel Passport package and all its dependencies.

After installing Laravel Passport, we’ll need to run the migration to create the necessary database tables. Run the following command to run the migration:

php artisan migrate

This will create the necessary tables in your database.

Finally, we’ll need to configure Laravel Passport by running the following command:

php artisan passport:install

This will create the encryption keys and other necessary components for Laravel Passport to work properly.

With these steps, you have successfully set up a Laravel application with Laravel Passport for API authentication. In the next step, we’ll create a login system that uses Laravel Passport to authenticate users.

Step 2: Creating a Login System

Next, we’ll create a login system that uses Laravel Passport to authenticate users. We’ll create a login form that sends an AJAX request to the Laravel API, which will return a JSON web token (JWT) if the user is authenticated.

Let’s start by creating a new route for the login form. Open the routes/web.php file and add the following route:

Route::get('/login', 'AuthController@showLoginForm')->name('login');

This route will call the showLoginForm method of the AuthController when a GET request is made to the /login URL.

Next, let’s create a new controller for the login form. Run the following command in your terminal to create a new controller:

php artisan make:controller AuthController

This will create a new AuthController in the app/Http/Controllers directory. Open the AuthController.php file and add the following code:

namespace App\Http\Controllers;use Illuminate\Http\Request;class AuthController extends Controller{ public function showLoginForm() { return view('auth.login'); }}

This code defines the showLoginForm method, which returns the auth.login view. We haven’t created the view yet, but we’ll do that next.

Create a new directory called auth in the resources/views directory. Then, create a new file called login.blade.php in the auth directory. Add the following code to the login.blade.php file:

@extends('layouts.app')@section('content')<div class="container"> <div class="row justify-content-center"> <div class="col-md-8"> <div class="card"> <div class="card-header">{{ __('Login') }}</div> <div class="card-body"> <form method="POST" action="{{ route('login-api') }}"> @csrf <div class="form-group row"> <label for="email" class="col-md-4 col-form-label text-md-right">{{ __('Email') }}</label> <div class="col-md-6"> <input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus> @error('email') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="form-group row"> <label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label> <div class="col-md-6"> <input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="current-password"> @error('password') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="form-group row mb-0"> <div class="col-md-6 offset-md-4"> <button type="submit" class="btn btn-primary"> Login </button> </div> </div> </form> </div> </div> </div> </div></div>@endsection

This code defines the login form view. It’s a simple form that includes fields for the email and password. When the form is submitted, it sends a POST request to the /login-api URL. We haven’t created the /login-api route yet, but we’ll do that next.

Let’s create a new route for the login API. Open the routes/api.php file and add the following route:

Route::post('/login', 'AuthController@login')->name('login-api');

This route will call the login method of the AuthController when a POST request is made to the /login-api URL.

Next, let’s create a new controller for the login API. Open the AuthController.php file and add the following code:

use Illuminate\Support\Facades\Auth;class AuthController extends Controller{ // ... public function login(Request $request) { $credentials = $request->only('email', 'password'); if (Auth::attempt($credentials)) { $user = Auth::user(); $token = $user->createToken('MyApp')->accessToken; return response()->json(['token' => $token]); } return response()->json(['error' => 'Invalid login credentials'], 401); }}

This code defines the login method, which authenticates the user using the Auth::attempt() method. If the authentication is successful, it creates a new access token using the createToken() method of the authenticated user, and returns the token in a JSON response. If the authentication is unsuccessful, it returns an error message in a JSON response with a status code of 401.

That’s it! Now you have a fully functional login system that uses Laravel Passport for API authentication. To test it out, you can navigate to the /login URL to see the login form, and submit the form with valid login credentials to receive an access token in a JSON response.

Step 3: Implementing Middleware Authorization

After creating the login system, we’ll implement middleware authorization to restrict access to specific routes and resources. We’ll create a middleware that checks for the presence of a valid JWT and denies access if the token is invalid or has expired.

First, we’ll create a middleware for the authorization check. Open the terminal and run the following command to create a new middleware:

php artisan make:middleware ApiTokenMiddleware

This will create a new middleware file named ApiTokenMiddleware.php in the app/Http/Middleware directory. Open the file and replace the code with the following:

<?phpnamespace App\Http\Middleware;use Closure;use Illuminate\Support\Facades\Auth;class ApiTokenMiddleware{ public function handle($request, Closure $next) { if (!$request->header('Authorization')) { return response()->json(['error' => 'Authorization token not found'], 401); } $token = explode(' ', $request->header('Authorization'))[1]; if (!Auth::guard('api')->check()) { return response()->json(['error' => 'Invalid authorization token'], 401); } return $next($request); }}

This middleware checks if the request header contains an authorization token. If it does not, the middleware returns a 401 Unauthorized response. If it does, the middleware extracts the token from the header and checks if it is a valid access token using the Auth::guard(‘api’)->check() method. If the token is not valid, the middleware returns a 401 Unauthorized response. If the token is valid, the middleware allows the request to proceed to the next middleware or route.

Next, we’ll apply this middleware to the getProfile method of the UserController. Open the UserController.php file and add the ApiTokenMiddleware middleware to the getProfile method:

<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;class UserController extends Controller{ public function getProfile(Request $request) { $user = $request->user(); return response()->json(['user' => $user]); }}
<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;use App\Http\Middleware\ApiTokenMiddleware;class UserController extends Controller{ public function getProfile(Request $request) { $this->middleware(ApiTokenMiddleware::class); $user = $request->user(); return response()->json(['user' => $user]); }}

With this code, the ApiTokenMiddleware middleware will be applied to the getProfile method of the UserController. This means that when the getProfile method is called, the middleware will first check if the request has a valid access token before allowing the method to proceed.

That’s it! Now you have implemented middleware authorization using Laravel Passport in your Laravel API.

Step 4: Fetching API Data

Finally, we’ll use Laravel’s built-in HTTP client to fetch data from an external API. We’ll add middleware authorization to ensure that only authenticated users can access the API, and we’ll display the API data on a protected route in our application.

First, let’s create a new route to handle the API request. Open the routes/api.php file and add the following route:

Route::get('/user', 'UserController@getProfile')->middleware('auth:api');

This route maps to the getProfile method of the UserController and applies the auth:api middleware to ensure that the request contains a valid access token.

Next, let’s create a new view to display the user profile data. Create a new file named profile.blade.php in the resources/views directory and add the following code:

<!DOCTYPE html><html><head> <title>User Profile</title></head><body> <h1>User Profile</h1> <div> <p>Name: <span id="name"></span></p> <p>Email: <span id="email"></span></p> </div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function() { $.ajax({ url: "/api/user", type: "GET", headers: { "Authorization": "Bearer {{ $accessToken }}" }, success: function(response) { $("#name").html(response.user.name); $("#email").html(response.user.email); } }); }); </script></body></html>

This view contains HTML code to display the user profile data and a jQuery script to fetch the data from the API using an AJAX request. The Authorization header in the AJAX request contains the access token retrieved from the AuthController earlier.

Finally, let’s create a new route to display the user profile view. Open the routes/web.php file and add the following route:

Route::get('/profile', function () { $accessToken = Auth::guard('api')->user()->createToken('Token Name')->accessToken; return view('profile', [ 'accessToken' => $accessToken, ]);});

This route maps to a closure that creates a new access token for the authenticated user and passes it to the profile.blade.php view using the $accessToken variable.

That’s it! Now when you access the /profile route in your browser, the view will make an AJAX request to the /api/user API endpoint, fetch the user profile data, and display it on the page.

In this tutorial, we showed you how to implement API-based authentication for middleware authorization in Laravel. By following these steps, you can provide secure access to your application’s resources and ensure that only authenticated users can access protected routes and data. With Laravel’s powerful set of tools for working with APIs, you can build scalable and secure web applications that meet the needs of modern businesses and users.

Implementing API-Based Authentication for Middleware Authorization in Laravel: A Step-by-Step Guide (2024)
Top Articles
Latest Posts
Article information

Author: Rubie Ullrich

Last Updated:

Views: 5761

Rating: 4.1 / 5 (72 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Rubie Ullrich

Birthday: 1998-02-02

Address: 743 Stoltenberg Center, Genovevaville, NJ 59925-3119

Phone: +2202978377583

Job: Administration Engineer

Hobby: Surfing, Sailing, Listening to music, Web surfing, Kitesurfing, Geocaching, Backpacking

Introduction: My name is Rubie Ullrich, I am a enthusiastic, perfect, tender, vivacious, talented, famous, delightful person who loves writing and wants to share my knowledge and understanding with you.