Install Laravel 10 Passport & Create REST API using Passport

Install Laravel 10 Passport & Create REST API using Passport

Laravel is a powerful PHP web application framework that allows developers to build robust and scalable applications with ease. Laravel Passport is a package that provides a complete authentication system for your Laravel applications using OAuth2. With Laravel Passport, you can easily create a RESTful API that can be consumed by any client, such as mobile apps or other web applications. In this article, we will go through the steps to install Laravel Passport and create a REST API using Passport.

Prerequisites:

Before you get started, make sure that you have a working installation of Laravel and Composer on your system.

Step 1: Install Laravel Passport

The first step to create a REST API using Passport is to install Laravel Passport. You can do this by running the following command in your terminal:

composer require laravel/passport

This will download and install the latest version of Laravel Passport in your project.

Step 2: Configure Laravel Passport

Once Laravel Passport is installed, you need to configure it for your application. You can do this by running the following command in your terminal:

php artisan passport:install

This command will create the necessary tables in your database and generate the encryption keys needed for Passport to work.

Step 3: Create a User Model

To use Laravel Passport, you need to create a User model for your application. You can do this by running the following command in your terminal:

php artisan make:model User -m

This will create a new User model in your app/Models directory and also create a migration file for the users table.

Step 4: Create API Routes

Next, you need to create API routes for your application. You can do this by adding the following code to your routes/api.php file:

Route::post('/login', 'AuthController@login');
Route::post('/register', 'AuthController@register');

Route::middleware('auth:api')->group(function () {
    Route::get('/user', function (Request $request) {
        return $request->user();
    });
});

The first two routes, /login and /register, are used for user authentication. When a POST request is sent to the /login endpoint, the AuthController@login method is called to verify the user’s credentials and generate an access token using Laravel Passport. Similarly, when a POST request is sent to the /register endpoint, the AuthController@register method is called to create a new user and generate an access token for that user.

The third route, /user, is an authenticated route that can only be accessed by users with a valid access token. The route is protected by the auth:api middleware, which ensures that the user making the request is authenticated. When a GET request is sent to the /user endpoint, the anonymous function defined in the route’s closure is called, which returns the authenticated user’s details using the Request object’s user() method.

Overall, this code provides a basic authentication system for a Laravel API and allows authenticated users to retrieve their details.

In this code, we have created two routes for login and registration, and a middleware group for authenticated routes.

Step 5: Create an AuthController

Now, you need to create an AuthController that will handle the authentication logic for your API. You can do this by running the following command in your terminal:

php artisan make:controller AuthController

This will create a new AuthController in your app/Http/Controllers directory.

Step 6: Add Authentication Logic to AuthController

Next, you need to add the authentication logic to your AuthController. You can do this by adding the following code to your AuthController:

use Illuminate\Http\Request;
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
            ]);
        } else {
            return response()->json([
                'error' => 'Unauthenticated'
            ], 401);
        }
    }

    public function register(Request $request)
    {
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password)
        ]);

        $token = $user->createToken('MyApp')->accessToken;

        return response()->json([
            'token' => $token
        ]);
    }
}

The login() method receives a Request object containing the user’s email and password. It then attempts to authenticate the user using Laravel’s Auth::attempt() method, which returns true if the user’s credentials are valid. If authentication is successful, the method retrieves the authenticated user’s details using Auth::user(), creates an access token for the user using Laravel Passport’s createToken() method, and returns the token as a JSON response. If authentication fails, the method returns a JSON response with an error message and a 401 Unauthorized status code.

The register() method receives a Request object containing the user’s name, email, and password. It creates a new User object using Laravel’s User::create() method and saves the user’s details to the database. It then generates an access token for the user using Laravel Passport’s createToken() method and returns the token as a JSON response.

Overall, this AuthController class provides a simple and secure authentication system for a Laravel API using Laravel Passport.

Note that in order for the login() and register() methods to work, you need to have a User model in your Laravel application that extends the Illuminate\Foundation\Auth\User class.

Also, make sure that you have installed and configured Laravel Passport correctly. You should have a personal_access_tokens table in your database, and the CreatePersonalAccessTokensTable migration should be run. Additionally, you need to call Laravel Passport’s Passport::routes() method in your AuthServiceProvider class’s boot() method to register the authentication routes.

To test the API, you can use tools like Postman or Insomnia to send requests to the /login and /register endpoints with valid credentials. You should receive a JSON response containing an access token for the authenticated user.

In conclusion, Laravel Passport provides a simple and secure way to implement authentication for your Laravel API. With its easy-to-use API and integration with Laravel’s existing authentication system, it allows developers to focus on building their application’s core logic while ensuring that their API is secure and scalable.

In this code, we have added the login and registration logic to our AuthController. The login method checks if the user’s credentials are valid, creates an access token using Passport, and returns it to the client. The register method creates a new user and generates an access token for that user.

Step 7: Test the API

Now, you can test your API by sending requests to the endpoints you have created. You can use tools like Postman or Insomnia to test your API.

To test the login endpoint, send a POST request to /api/login with the email and password of a registered user. The API should respond with an access token.

To test the authenticated endpoint, send a GET request to /api/user with the access token in the Authorization header. The API should respond with the details of the authenticated user.

Conclusion:

In this article, we have gone through the steps to install Laravel Passport and create a REST API using Passport. With Laravel Passport, you can easily create a secure and scalable API that can be consumed by any client. Laravel Passport provides a complete authentication system for your Laravel applications, making it easier for developers to focus on building their application’s core logic.

This Article Ideas has been taken from the following websites; which are following:

https://www.itsolutionstuff.com/post/laravel-10-rest-api-with-passport-authentication-tutorialexample.html

Laravel 10 REST API with Passport Authentication

https://www.toptal.com/laravel/passport-tutorial-auth-user-access

https://laravel.com/docs/10.x/passport

https://www.cloudways.com/blog/rest-api-laravel-passport-authentication/

https://www.positronx.io/laravel-rest-api-with-passport-authentication-tutorial/

Laravel Passport: A tutorial and example build

https://techsolutionstuff.com/post/rest-api-with-passport-authentication-in-laravel-9

Create REST API in Laravel with authentication using Passport

Comments

Leave a Reply

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