This tutorial is about Laravel 6 passport authentication. Laravel 6.0 is the latest release of Laravel framework. and includes compatibility with Laravel vapor. Laravel vapor is auto-scaling, serverless deployment platform for Laravel powered by AWS. and it has been so much fun discovering I have been writing a lot of APIs recently but for some reasons most of them haven’t started making me enough cash. I mostly find myself working in the Laravel and NodeJs environment. I recently had to try out Django and LeafletJs because of a geospatial related project my company was onboarding for another company. I should begin to get my hand dirty with some python once that contract is completed.
I decided to do this tutorial to share my experiences on the various version releases of the Laravel framework over the past 3 years since I started working with the framework.
This post assumes you have a working Laravel 6 project and you want to implement API authentication using Passport. This is a not a beginner’s introduction to Laravel tutorial.
The first thing we would do is to install the Laravel Passport into our project using composer.
composer require laravel/passport
This installs passport into our composer file in the root our project folder.
After the installation is complete, we get the default passport migration tables in our database. Run php artisan command
php artisan migrate
I will be using phpMyAdmin and TablePlus as my sql client. You may also use mysql workbench if you prefer that. So, let’s first check out our migrations we had before we run the command.
TablePlus is easy to install and I like it because of the dark mode and the fact that it supports a lot of databases. And the it is not free but you can enjoy the free version with some limitations. Or you can just buy the license.
You would notice we have, just the default user table was in our database before we run our migrations to get the default passport migrations.
Next step is to install passport into the project. This will create the encryption keys for security (public and private key). You can find this in your storage folder of your project root directory.
Run artisan command
php artisan passport:install
The next thing we would do is to configure passport into our project. This configuration will be done to our providers, configurations and models. We add passport to our auth providers, auth configuration and user models. Since it is only the user we would be authenticating with passport. So basically, we are going to inherit a few classes from passport.
- Authentication Service Provider file (AuthServiceProvider.php)
- Authentication Configuration file
- Our User Model
In our AuthSerivceProvider we add;
Passport::routes()
In our auth.php folder inside our configurations folder we add passport as our api authentication guard for users.
And in our user model we add the HassApiTokens class on the user model.
So, let’s get going,
We will first create an authentication controller where all our auth logics will sit. Laravel create a controller class that all your other controllers extend. I prefer to begin by creating a custom controller. All my other controllers would extend my custom controller and my custom controller will rather extend the default Laravel controller.
This is because I may require some custom methods in my project later. So, I first create that controller but we would not use it in this tutorial. I will call it BedestonController. I use it to customize how my api return responses. This custom controller for instance saves me a few lines of codes for repetitive methods.
Run the artisan command;
php artisan make:controller BedestonController
php artisan make:controller UserAuthController
For the purpose of this tutorial, we are going to ignore the custom controller (BedestonController) at the moment. We will use it in later tutorial.
API scope is defined by adding the tokencan method in the boot method of the AuthServiceProvider. This method accepts an array of scope and scope definitions. This is just another way of saying what can a user issued to the user do?
The next thing is to check scope on request
We will do this by adding two of the middelwares that passport provide to route Middleware property in our kernel.
Our Kernel.php file is located here app/Http/Kernel.php
The next thing is to add our user authentication route to our api route (api.php) and secure our api endpoints with our middleware
Your api.php file can be located routes folder at the root of your project
routes/api.php
We can finally test our API in postman.
- Register
- Login
- Logout
UserAuthController.php
<?php
namespace AppHttpControllers;
//use AppHttpControllersBaseController as BedestonController;
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;
use AppUser;
use Validator;
class UserAuthController extends Controller
{
/**
* Handles User Registration Request
*
* @param Request $request
* @return IlluminateHttpResponse
*/
public function userRegister(Request $request)
{
$input = $request->all();
$validator = Validator::make($input,
[
‘name’ => ‘required’,
’email’ => ‘required|email’,
‘password’ => ‘required’,
‘c_password’ => ‘required|same:password’
]);
if ($validator->fails())
{
return response()->json($validator->errors(), 417);
}
$user = User::create(
[
‘name’ => $request->name,
’email’ => $request->email,
‘password’ => bcrypt($request->password),
]);
$data[‘name’] = $user->name;
$data[‘token’] = $user->createToken(‘StemxusApp’, [‘user-scope’])->accessToken;
return response()->json(
[
‘success’ => true,
‘data’ => $data,
‘message’ => ‘User Registered Successfully’
]);
}
/**
* Handles User Login Request
*
* @param Request $request
* @return IlluminateHttpResponse
*/
public function userLogin(Request $request)
{
$input = $request->all();
$validator = Validator::make($input,
[
’email’ => ‘required|email’,
‘password’ => ‘required’,
]);
if($validator->fails())
{
return response()->json($validator->errors(), 417);
}
$credentials = $request->only(
[
’email’,
‘password’
]);
if(Auth::attempt($credentials))
{
$user = Auth::user();
$data[‘token’] = $user->createToken(‘StemxusApp’,[‘user-scope’])->accessToken;
return response()->json([
‘success’ => true,
‘data’ => $data,
‘message’ => ‘User logged in Successfully’,
], 200);
}
else
{
return response()->json([
‘success’ => false,
‘error’ => ‘UnAuthorised’,
‘message’ => ‘User Not Registered’,
], 401);
}
}
/**
* Handles User Logout Request
*
* @param Request $request
* @return IlluminateHttpResponse
*/
public function userLogout(Request $request)
{
$request->user()->token()->revoke();
return respose()->json(
[
‘message’ => ‘Successfully logged user out’
]);
}
/**
* Handles Administrator Registration Request
*
* @param Request $request
* @return IlluminateHttpResponse
*/
public function adminRegister(Request $request)
{
$validator = Validator::make($request->all(),
[
‘name’ => ‘required’,
’email’ => ‘required|email’,
‘password’ => ‘required’,
‘c_password’ => ‘required|same:password’,
]);
if($validator->fails())
{
return response()->json($validator->errors(), 417);
}
$user = User::create(
[
‘name’ => $request->name,
’email’ => $request->email,
‘password’ => bcrypt($request->password),
]);
$data[‘name’] = $user->name;
$data[‘token’] = $user->createToken(‘StemxusApp’, [‘*’])->accessToken;
return response()->json(
[
‘success’ => true,
‘data’ => $data,
‘message’ => ‘User Registered Successfully’,
],200);
}
/**
* Handles Administrator Login Request
*
* @param Request $request
* @return IlluminateHttpResponse
*/
public function adminLogin(Request $request)
{
$input = $request->all();
$validator = Validator::make($input,
[
’email’ => ‘required|email’,
‘password’ => ‘required’,
]);
if($validator->fails())
{
return response()->json($validator->errors(), 417);
}
$credentials = $request->only(
[
’email’,
‘password’
]);
if(Auth::attempt($credentials))
{
$user =Auth::user();
$data[‘token’] = $user->createToken(‘StemxusApp’, [‘*’])->accessToken;
return response()->json(
[
‘success’ => true,
‘data’ => $data,
‘message’ => ‘User logged in Successfully’,
],200);
}
else {
return response()->json(
[
‘success’ => false,
‘error’ => ‘UnAuthorised’,
‘message’ => ‘User Not Registered’,
], 401);
}
}
/**
* Handles Admin Logout Request
*
* @param Request $request
* @return IlluminateHttpResponse
*/
public function adminLogout(Request $request)
{
$request->user()->token()->revoke();
return response()->json(
[
‘message’ => ‘Successfully logged user out’
]);
}
}