Create API Authentication With Laravel Passport
Learn how to setup and configure Laravel Passport for API Authentication and RESTful APIs in a Laravel application.
Join the DZone community and get the full member experience.
Join For FreeIn this tutorial, we will see how to use Laravel passport authentication in your Laravel application.
Let’s see how to setup and configure Laravel Passport for API authentication and RESTful APIs in a Laravel application.
Creating a New Project
composer create-project --prefer-dist laravel/laravel passport
Install Package
xxxxxxxxxx
composer require laravel/passport
Service Provider
You need to add Service Provider in the config/app.php
file. So, open the file and add the Service Provider in the providers
array.
xxxxxxxxxx
'providers' => [
....
Laravel\Passport\PassportServiceProvider::class,
]
Migration and Installation
Set up database credentials in the .env
file. Run the migration command to migrate schemas to your database.
xxxxxxxxxx
php artisan migrate
Next, it is required to install passport
using the command below. It will generate encryption keys required to generate secret access tokens.
xxxxxxxxxx
php artisan passport:install
Passport Configure
Add Laravel\Passport\HasApiTokens
trait to your User
model. It will provide few helper methods.
xxxxxxxxxx
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
/**
* 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',
];
}
Add Passport::routes
method in the boot method of your AuthServiceProvider
. It will generate necessary routes. This is how the app/Providers/AuthServiceProvider.php
will look like after changes.
xxxxxxxxxx
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
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();
}
}
In the config/auth.php
file, set driver to the passport.
xxxxxxxxxx
return [
....
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
....
]
Create Route
Add routes in the routes/api.php
file.
xxxxxxxxxx
Route::post('login', 'PassportController@login');
Route::post('register', 'PassportController@register');
Route::middleware('auth:api')->group(function () {
Route::get('user', 'PassportController@details');
Route::resource('products', 'ProductController');
});
Create Controller for Authentication
Create Passport Controller by running the following command.
xxxxxxxxxx
php artisan make:controller PassportController
Copy the contents below to app/Http/Controllers/PassportController.php
xxxxxxxxxx
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
class PassportController extends Controller
{
/**
* Handles Registration Request
*
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function register(Request $request)
{
$this->validate($request, [
'name' => 'required|min:3',
'email' => 'required|email|unique:users',
'password' => 'required|min:6',
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password)
]);
$token = $user->createToken('TutsForWeb')->accessToken;
return response()->json(['token' => $token], 200);
}
/**
* Handles Login Request
*
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function login(Request $request)
{
$credentials = [
'email' => $request->email,
'password' => $request->password
];
if (auth()->attempt($credentials)) {
$token = auth()->user()->createToken('TutsForWeb')->accessToken;
return response()->json(['token' => $token], 200);
} else {
return response()->json(['error' => 'UnAuthorised'], 401);
}
}
/**
* Returns Authenticated User Details
*
* @return \Illuminate\Http\JsonResponse
*/
public function details()
{
return response()->json(['user' => auth()->user()], 200);
}
}
Testing
Now thar our logic is complete, let’s start testing. We will be testing it on PHP development server, but you can use virtual host if you want. Run the following command to serve the application on the PHP development server.
xxxxxxxxxx
php artisan serve
Now, let’s test our API endpoints using an API testing tool like Postman.
Published at DZone with permission of Razet Jain. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments