In this tutorial we will develop a full API authentication system which can be used by any application which is able to perform requests (React, Vue or Angular for instance).
We will use Laravel 5.7 and its Passport package: https://laravel.com/docs/5.7/passport
Install Laravel 5.7 via composer:
composer create-project --prefer-dist laravel/laravel api-authentification
Configure the connection to the database in our .env file:
Install the basic authentication system integrated in Laravel and Laravel Passport:
composer require laravel/passport
php artisan make:auth
php artisan passport:install
php artisan migrate
Laravel\Passport\HasApiTokens trait to our
App\User model and the
Passport::routesmethod within the
boot method of our
app/AuthServiceProvider like that:
And finally set the
driver option of the
api authentication guard to
passport like that:
Laravel Passport is now installed and configured, now we will create a controller to:
- Create an account
- Log in
- Sign out
Let’s go! Create your new controller:
php artisan make:controller Api/AuthController
In this new controller we will create 3 functions: register, login and logout.
Add at the top of the file:
Create the 3 functions:
Tadam! It’s done.
Before testing, and because we use Laravel only as an API provider, we are going to force all routes to return json. We will use Alex Lichter’s method.
Create a middleware:
php artisan make:middleware ForceJsonResponse
Add to the
$routeMiddleware of the
We can now add our routes in
routes/api.php. The register and login routes are public while the logout route will only be accessible when the user is logged in.
So we have:
We will now test that everything is ok with Postman (you can use any other tool to simulate http requests).
We can now check that the route
/api/user is not accessible without authentication:
Creating an account:
The register route returns a token (because it automatically logs you) but we will regenerate it with the login route to check that works well.
We log in with the account we just created:
We copy the token returned to us (this token proves that we are connected).
We go back to the window where we tested the route
/api/user by adding this time our token. For that, go in the tab "Authorization" and select "Bearer Token", paste the token in the input "Token":
Just press “Send”, and…
If you want to go further you can find a lot of information on the features of Laravel Passport here: https://laravel.com/docs/5.7/passport
Feel free to ask me your questions in the comment section 🙂