Sobatcoding.com - Tutorial Menggunakan JWT (JSON Web Token) Pada Lumen API
JWT (Json Web Token) adalah sebuah token menggunakan JSON (Javascript Object Notation), lalu token ini memungkinkan kita untuk mengirimkan data yang dapat diverifikasi oleh dua pihak atau lebih.
JWT bisa kita gunakan sebagai authentifikasi saat akses ke sebuah REST API. Karena di dalam JWT dapat menyimpan informasi yang dibutuhkan (sperti informasi user) dan juga kita bisa set untuk expired dari token JWT tersebut.
Bagaiamana cara penggunaan JWT dengan Lumen Laravel? Berikut langkah-langkahnya:
Jalankan perintah berikut untuk instal package jwt lumen:
composer require tymon/jwt-auth
Selanjutnya untuk config kita copy config file dari folder vendor/tymon/jwt-auth/config/config.php
ke folder config kemudian rename menjadi jwt.php. Jika belum ada folder config buat terlebih dahulu folder config satu level dengan folder app.
Selanjutnya kita register config tersebut dengan cara buka file app.php di folder bootstrap, kemudian tambahkan kode berikut sebelum middleware:
$app->configure('jwt');
Tambahkan line berikut untuk register service jwt Register Service Providers section.
// Uncomment this line
$app->register(App\Providers\AuthServiceProvider::class);
// Add this line
$app->register(Tymon\JWTAuth\Providers\LumenServiceProvider::class);
Un commnet juga line berikut:
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
]);
Jalan kan perintah berikut untuk generate secret key
php artisan jwt:secret
Perintah di atas otomatis upadte file .env dengan JWT_SECRET=key
Tambahkan file auth.php dan simpan di folder config, kemudian tambahkan kode berikut:
<?php
return [
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => \App\Model\Users::class
]
]
];
Jangan lupa register juga untuk file auth.php
$app->configure('auth');
Buat sebuah model bernama Users dan simpan di folder app\Models, kemudian tambahkan kode berikut:
<?php
namespace App\Models;
use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Model;
use Laravel\Lumen\Auth\Authorizable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class Users extends Model implements JWTSubject, AuthenticatableContract, AuthorizableContract
{
use Authenticatable, Authorizable;
protected $table = 'm_users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'username', 'name', 'address', 'phone'
];
/**
* Get the identifier that will be stored in the subject claim of the JWT.
*
* @return mixed
*/
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* @return array
*/
public function getJWTCustomClaims()
{
return [];
}
}
Buat sebuah controller untuk generate token, sebagai contoh kita buat AuthController.php. Biasanya untuk auth menggunakan field email dan password tapi kali ini kita akan membuat auth JWT menggunakan username dan password. Untuk kode adalah sebagai berikut:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Validator;
use App\Models\Users;
class AuthController extends Controller
{
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'username' => 'required|min:4',
'password' => 'required|min:6'
],
[
'required' => ':attribute harus diisi',
'min' => ':attribute minimal :min karakter',
]);
if ($validator->fails()) {
$resp = [
'metadata' => [
'message' => $validator->errors()->first(),
'code' => 422
]
];
return response()->json($resp, 422);
die();
}
$user = Users::where('username', $request->username)->first();
if($user)
{
if( Crypt::decrypt($user->password) == $request->password)
{
$token = \Auth::login($user);
$resp = [
'response' => [
'token'=> $token
],
'metadata' => [
'message' => 'OK',
'code' => 200
]
];
return response()->json($resp);
}else{
$resp = [
'metadata' => [
'message' => 'Username Atau Password Tidak Sesuai',
'code' => 401
]
];
return response()->json($resp, 401);
}
}else{
$resp = [
'metadata' => [
'message' => 'Username Atau Password Tidak Sesuai',
'code' => 401
]
];
return response()->json($resp, 401);
}
}
}
Tambahkan route baru seperti berikut:
$router->post('/login', 'AuthController@login' );
Dan berikut hasil saat kita jalankan dan uji test menggunakan postman:
Token yang ter generate adalah :
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3Q6ODA4MFwvbG9naW4iLCJpYXQiOjE2NDkzOTEyNzYsImV4cCI6MTY0OTM5NDg3NiwibmJmIjoxNjQ5MzkxMjc2LCJqdGkiOiIwRzFDdzFjMjJJcEw2T2YxIiwic3ViIjoxLCJwcnYiOiJmNjRkNDhhNmNlYzdiZGZhN2ZiZjg5OTQ1NGI0ODhiM2U0NjI1MjBhIn0.8P7U1RAQKWz_YXXteqbl-q7t33Pap6WeHkrw5cvp7AY
Untuk menambahkan atau set expired time token JWT kita bisa edit di file config/jwt.php pada line berikut.
/*
|--------------------------------------------------------------------------
| JWT time to live
|--------------------------------------------------------------------------
|
| Specify the length of time (in minutes) that the token will be valid for.
| Defaults to 1 hour.
|
| You can also set this to null, to yield a never expiring token.
| Some people may want this behaviour for e.g. a mobile app.
| This is not particularly recommended, so make sure you have appropriate
| systems in place to revoke the token if necessary.
| Notice: If you set this to null you should remove 'exp' element from 'required_claims' list.
|
*/
'ttl' => env('JWT_TTL', 60),
Untuk default expired time token JWT adalah dalam menit yaitu 60 menit. Kalian bisa ubah sesuai kebutuhan kalian.
Untuk full source code bisa kalian cek di link berikut: https://github.com/sobatcoding21/Lumen-API/
Sekian tutorial kali ini dan semoga bermanfaat.
Komentar 2