Contents
- Introduction:
- Prerequisite:
- Step 1: Install Laravel 7 Using Composer
- Step 2: Install Laravel Passport
- Step 3: Set Database Configuration
- Step 4: Execute Migration
- Step 5: Create Encryption Keys
- Step 6: Update User Model
- Step 7: Update AuthServiceProvider
- Step 8: Set API Driver Option
- Step 9: Create Authentication Controller
- Step 10: Create API routes
- Lets test the API Authentication
Introduction:
Hi! Today we will learn how to create an authentication on our Laravel API. But before that let has a discussion about API and what is Laravel Passport.
API stands for Application Program Interface, API is an interface which allows applications exchange data. To make it more clear, API are set of functions that can be used by programmer to build software and applications.
Since our API is stateless and doesn’t have a sessions we will be using the Laravel Passport. It is an Oauth2 server that will be used for API authentication.
Prerequisite:
- Composer
- MySQL
- PHP >= 7.2.5
Before proceeding on this tutorial, you must have an environment already setup to run and install Laravel. If you haven’t, please do read my blog –How to Install Laravel 7 in Windows with XAMPP and Composer Easy Tutorial.
Step 1: Install Laravel 7 Using Composer
First, select a folder that you want the Laravel to be installed then execute this command on Terminal or CMD to install Laravel 7:
composer create-project --prefer-dist laravel/laravel api-passport
Step 2: Install Laravel Passport
Move to the created laravel up and install the Laravel Passport. Execute this command to install Passport:
composer require laravel/passport
Step 3: Set Database Configuration
Open the .env file and set database configuration:
.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your database name(api_passport)
DB_USERNAME=your database username(root)
DB_PASSWORD=your database password(root)
Step 4: Execute Migration
The Laravel passport has its database migrations directory. The passport migration will create tables to store clients and access tokens.
Run the migration by executing the migrate
Artisan command:
php artisan migrate
Step 5: Create Encryption Keys
Let create the encryption keys for generating secure access tokens. Run this command:
php artisan passport:install
The command will create personal access and password grant to be used in generating access tokens.
Step 6: Update User Model
after successfully running passport:install, Add the Laravel/Passport\HasApiTokens trait to the App\User model. The trait provides helper methods for the model to inspects the authenticated user’s token and scopes.
app/User.php
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;//Add this line
class User extends Authenticatable
{
use Notifiable, HasApiTokens; //Add HasApiTokens
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Step 7: Update AuthServiceProvider
Add Passport:routes method in AuthServiceProvider boot method. This method will handle the registration of necessary routes to issue and revoke access tokens,clients and personal access tokens.
app/Providers/AuthServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use Laravel\Passport\Passport;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
Passport::routes();
//
}
}
Step 8: Set API Driver Option
Set to passport the driver option of api authentication guard. The the incoming API request will be authenticated by Passport’s TokenGuard.
config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
'hash' => false,
],
],
Step 9: Create Authentication Controller
Now, Lets create a controller that will be responsible for registering and authenticating users. Run this command:
php artisan make:controller Api/AuthenticationController
then open the AuthenticationController file, and add this codes:
app/Http/Controllers/Api/AuthenticationController.php
<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\User;
class AuthenticationController extends Controller
{
public function register(Request $request)
{
$formData = $request->validate([
'name' => 'required|max:55',
'email' => 'email|required|unique:users',
'password' => 'required|confirmed'
]);
$formData['password'] = bcrypt($request->password);
$user = User::create($formData);
$accessToken = $user->createToken('accessToken')->accessToken;
return response()->json([ 'user' => $user, 'accessToken' => $accessToken]);
}
public function login(Request $request)
{
$credentials = $request->validate([
'email' => 'email|required',
'password' => 'required'
]);
$response = [];
if (Auth::attempt($credentials))
{
$accessToken = Auth::user()->createToken('accessToken')->accessToken;
$response = [
'user' => Auth::user(),
'access_token' => $accessToken
];
} else {
$response = [ 'status' => 'Invalid Email or Password'];
}
return response()->json($response);
}
}
Step 10: Create API routes
Finally, let create a route for the user to register and login.
routes/api.php
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('/register', 'Api\AuthenticationController@register');
Route::post('/login', 'Api\AuthenticationController@login');
Lets test the API Authentication
We will be using Postman for our testing, but you can test it on the way you prefer.
Register
Login
The access token will be used when accessing a api route that need authentication. Try accessing the /api/user route.
Now our API authentication is done.