Laravel
authentication with Passport
What is Laravel Passport? Laravel Passport is an OAuth 2.0 server
implementation for API authentication using Laravel. Since tokens are
generally used in API authentication, Laravel Passport provides an easy and
secure way to implement token authorization on an OAuth 2.0 server.
Build a Secure API in PHP Using Laravel Passport
Laravel
Passport provides a full 0Auth2 server
implementation for Laravel applications. With it, you can easily generate a
personal access token to uniquely identify a currently authenticated user. This
token will then be attached to every request allowing each user access
protected routes.
Create
New Project
composer
create-project --prefer-dist laravel/laravel laravelbackendapi
Depending on your preferred choice, the
preceding commands will create a new folder named laravel-backend-api
within the development folder, you installed Laravel
and its dependencies in.
You can move into the newly created folder
and run the application using the in built-in Laravel Artisan command as shown here:
// move into the project
$
cdlaravelbackendapi
// run the application
$ php artisan serve
Navigate to http://localhost:8000
from your browser to view the welcome page:
Create a Database and
Connect to It
Now that Laravel is installed and running,
the next step is to create a connection to your database. First, ensure that
you have created a database and then update the values of the following
variables within the .env
file:
- DB_DATABASE
- DB_USERNAME
- DB_PASSWORD
The database is all set, but before we start
building our API, we need to install and configure Laravel Passport.
$
composerrequire laravel/passport
Once the installation is complete, a new migration file containing the tables needed to store clients and access tokens will have been generated for your application. Run the following command to migrate your database:
$ php artisan migrate
Next, to create the encryption keys needed to generate secured access tokens, run the command below: