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!

source: laravel.com

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 — laravel.com

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

Tools

  • XAMPP
  • 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.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=larapassport
DB_USERNAME=root
DB_PASSWORD=

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()
{
$this->registerPolicies();
Passport::routes();
}
}

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'],
]);
if($validator->fails()){
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){
if(Auth::user()){
$user = Auth::user()->token();
$user->revoke();
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!

--

--

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