In this article, I will be creating an API with Laravel Passport. Laravel Passport provides an easy way to perform API authentication. You will be learning how to build an API in Laravel passport with password grant tokens and how to generate a token for a user. This token is used to authenticate the user.
Postman is the tool that I will be using to send requests to the API.
Let’s start by installing Laravel Passport via Composer.
composer require laravel/passport
Laravel Passport will create its own tables to store client and access tokens. So we should migrate the database after installing Passport.
php artisan migrate
Next, we will have to create the encryption keys that are needed to generate secure access tokens. We can do this by executing the following command:
php artisan passport:install
Add the HasApiTokens trait to the User model.
In the AuthServiceProvider we should call Passport::routes() within the boot method. This will register routes that are needed to issue access tokens and revoke tokens.
There is one more thing that we need to do before we can start building the API. In the config/auth.php change the guards.api.driver to passport.
Defining a route
For now, we will be using a very simple example in the routes/api.php.
Creating a user
To be able to test the endpoint we have to create a user. We will be creating a command to do that for us. Let’s start by creating the command:
php artisan make:command CreateUserCommand
The command will create a user and a token based on some options that have to get passed to the command.
As you can see we have to pass four options to the command:
token, which is the name of the token
Create a user by executing the following command:
php artisan user:create –name=Laravel –firstname.lastname@example.org –password=secret –token=LaravelToken
After executing the command you should see a token in your console. Copy this token.
Make sure that the token that gets printed in the console does not contain any line breaks.
Sending a request to the API
To send a GET request to the /api/books endpoint we have to add the token that you just copied as a Bearer token. To do that in Postman, click on the Authorization tab and select Bearer Token in the Type select box.