Membuat API Otentikasi Laravel (Laravel Rest API Authentication with Passport)

Halo semua!

In this article, I will share How to make Rest API Authentication Laravel with Passport. Basically, we will be creating a Login, Register and Logout API endpoint. Mari belajar bersama!


What is Laravel Passport?

Laravel Passport provides a full OAuth2 server implementation for your Laravel application in a matter of minutes. Passport is built on top of the League OAuth2 server that is maintained by Andy Millington and Simon Hamp —

Next, run a fresh Laravel instalation. In this article, I will use Laravel 5.8


  • Postman. I suggest you to use Postman to test your API

Installing Laravel

Open your command line and run the command:

composer create-project --prefer-dist laravel/laravel lara_passport "5.8.*"

After successfull instalation, create your own databse and edit the database config section in .env file.


Installing Laravel Passport

Within your project directory, run the command:

composer require laravel/passport

Run migration

php artisan migrate

Create Encryption Keys

Next, you should run the passport:install on your command line

php artisan passport:install

After running this command, import Laravel\Passport\HasApiTokens on your App/User model. This trait will provide a few helper methods to your model which allow you to inspect the authenticated user’s token. Here is my full code

<?phpnamespace App;use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
use HasApiTokens, Notifiable;
protected $fillable = [
‘name’, ‘email’, ‘password’,
protected $hidden = [
‘password’, ‘remember_token’,
protected $casts = [
‘email_verified_at’ => ‘datetime’,

Next, insert Passport::routes method on the boot method of app/Providers/AuthServiceProvider.php. This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens. This is my full code

<?phpnamespace App\Providers;use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Schema;
use Laravel\Passport\Passport;
class AuthServiceProvider extends ServiceProvider
protected $policies = [
‘App\Model’ => ‘App\Policies\ModelPolicy’,
public function boot()

In your config/auth.php set the driver option of the api authentication guard to passport. Change your configuration like this

‘guards’ => [
‘web’ => [
‘driver’ => ‘session’,
‘provider’ => ‘users’,
‘api’ => [
‘driver’ => ‘passport’,
‘provider’ => ‘users’,

Start Creating API Endpoints

Open your route/api.php and change your route like this

<?phpuse Illuminate\Http\Request;Route::group(['prefix' => 'v1'], function(){
Route::post('login', 'UsersController@login');
Route::post('register', 'UsersController@register');
Route::get('logout', 'UsersController@logout')->middleware('auth:api');

Next, we will create API for login, register and logout. Run the command to make a UsersController

php artisan make:controller UsersController

Login Function

<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;
use Validator;
use App\User;
use Auth;
class UsersController extends Controller
public function login(){
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
$user = Auth::user();
$success['token'] = $user->createToken('appToken')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user,
} else{
return response()->json([
'success' => false,
'message' => 'Invalid Email or Password',
], 401);

Register Function

public function register(Request $request){
$validator = Validator::make($request->all(), [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8'],
return response()->json([
'success' => false,
'message' => $validator->errors(),
], 401);
$input = $request->all();
$input['password'] = bcrypt($input['password']);
$user = User::create($input);
$success['token'] = $user->createToken('appToken')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user

Logout Function

public function logout(Request $request){
$user = Auth::user()->token();
return response()->json([
'success' => true,
'message' => 'Logout successfully',
} else{
return response()->json([
'success' => false,
'message' => 'Unable to Logout',

Test the API

Now, it’s time to test the API that we have created. Start the server with type command php artisan serve.

Open Postman, and enter the URL that have been you made on API routes.

If you are using Laravel 5.8 and get some issues like this

Replicating claims as headers is deprecated and will removed from v4.0.

Open your command line and type this

composer require lcobucci/jwt=3.3.3

Test again on Postman, and boom!

Register successfully

Login Test

Login successfully

Logout Test

Copy the token value, and set the header on Postman

Set header with Authorization
Logout successfully

Hope this is usefull, you can build as many secured APIs as you wish using Laravel.

Having issues? Do let me know. Write on comments, cheers!

Thank you very much! Terima kasih!




IT Enthusiast | Developers

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Kioptrix Level 1

Automating Repetitive Tasks with Scripts

Awesome tricks every Python coder should know

Golang Application Tracing in Instana

eLearning development with Umbraco

CS373 Spring 2021: Vishal Tak

Base/detail: Creating dashboards with formulas

Introduction to Point of Presence and Network Access Point

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Rheadavin Adhiskara

Rheadavin Adhiskara

IT Enthusiast | Developers

More from Medium

Laravel Secure Rest API with Swagger

How to add, update and delete from JSON array in Javascript — CRUD

Laravel Security Vulnerabilities Challenge And How to Address Them Using

How to Clone Laravel Project from Git Repository and Run it on Local Machine