Laravel 8 REST API with Passport Authentication Tutorial

Building a robust and secure REST API is a fundamental aspect of modern web development. Laravel, a PHP web application framework, has proven itself as a solid choice for developers seeking to create scalable and maintainable applications. With its release of version 8, Laravel provides a powerful set of tools for implementing authentication and authorization in your application.

In this tutorial, we will walk you through the process of creating a RESTful API using Laravel 8 and Passport, a popular authentication package that simplifies OAuth2 implementation.

By the end of this tutorial, you will have a fully functioning API with Passport authentication, allowing you to manage and secure user access.

Before diving into the tutorial, ensure that you have the following prerequisites in place:

 

Laravel 8 Installation

To get started, you will need to have Laravel 8 installed on your development environment. You can follow the official Laravel installation guide here.

 

Passport Package Installation

Additionally, you will need to install the Passport package. You can do this by running the following command:

composer require laravel/passport

Setting Up Passport

With Laravel and Passport installed, it’s time to set up Passport for your application.

 

Configuration

First, you need to configure the application by adding the Passport::routes method within the boot method of your AuthServiceProvider. This will register the necessary routes for Passport:

use Laravel\Passport\Passport;

public function boot()
{
    $this->registerPolicies();
    Passport::routes();
}

Migration

Next, you’ll need to run the Passport migration to create the necessary database tables:

php artisan migrate

Then, run the following command to generate the encryption keys required for token generation:

php artisan passport:install

Creating API Routes

Now that Passport is set up, you can start creating the API routes. In your routes/api.php file, add the following routes:

Route::post('register', 'App\Http\Controllers\Api\RegisterController@register');
Route::post('login', 'App\Http\Controllers\Api\LoginController@login');
Route::middleware('auth:api')->group(function () {
    Route::get('user', 'App\Http\Controllers\Api\UserController@details');
});

Building API Controllers

With your routes defined, you’ll need to create the corresponding controllers to handle user registration, authentication, and fetching user details.

 

RegisterController

Create a new RegisterController and add the following code:

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class RegisterController extends Controller
{
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8|confirmed',
        ]);

        if ($validator->fails()) {
            return response(['errors' => $validator->errors()->all()], 422);
        }

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

        $token = $user->createToken('Laravel8PassportAuth')->accessToken;
        return response(['user' => $user, 'access_token' => $token], 200);
    }
}

 

LoginController

Create a new LoginController and add the following code:

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');

        if (Auth::attempt($credentials)) {
            $user = Auth::user();
            $token = $user->createToken('Laravel8PassportAuth')->accessToken;
            return response(['user' => $user, 'access_token' => $token], 200);
        } else {
            return response(['error' => 'Unauthorised'], 401);
        }
    }
}

 

UserController

Create a new UserController and add the following code:

use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function details(Request $request)
    {
        return response(['user' => $request->user()], 200);
    }
}

Testing API Endpoints

With your controllers set up, you can now test your API endpoints using a tool like Postman or curl.

 

Registration

Send a POST request to /api/register with the required fields to register a new user.

 

Authentication

Send a POST request to /api/login with the user’s email and password to authenticate the user and receive an access token.

 

Accessing Protected Routes

Use the access token received during authentication to access the protected /api/user route by including it in the Authorization header as a Bearer token.

 

Conclusion

Congratulations! You’ve successfully built a RESTful API using Laravel 8 and Passport authentication. With this foundation, you can now expand your API to include more advanced features and functionality.

 

FAQs

 

  1. What is Laravel Passport?Laravel Passport is a package that simplifies OAuth2 implementation for Laravel applications, allowing developers to easily secure their APIs with access tokens.
  2. What is the purpose of the access token?Access tokens are used to authenticate and authorize users, providing secure access to protected resources within your API.
  3. Can I use Passport with other Laravel versions?Yes, Passport is compatible with other Laravel versions. However, some configuration and implementation details may differ between versions.
  4. How can I revoke a user’s access token?You can revoke a user’s access token by calling the revoke method on the token instance, or by deleting the token from the database.
  5. Can I use Passport for other types of authentication besides OAuth2?While Passport is primarily designed for OAuth2, it can also be used for other authentication methods by customizing its behavior through middleware and event listeners. However, for simpler authentication methods, other Laravel packages like Sanctum might be more suitable

 

Leave a Comment

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