www.WarungProgram.com

Tempat Belajar Bahasa Pemrograman Dari Dasar


Tutorial Menggunakan Autentikasi JWT Pada Laravel

Penulis : Zulfikar Kategori : Uncategorized

Tutorial Menggunakan Autentikasi JWT Pada Laravel

Pada Tutorial kali ini kita akan belajar menggunakan autentikasi Json Web Token (JWT) pada framework php Laravel.

 

Sekilas tentang JWT

JWT atau Json Web Token adalah metode untuk untuk autentikasi antar aplikasi sesuai standar RFC 7519.

Untuk lebih lengkap nya silahkan kunjungi situ resminya https://jwt.io/

 

Instalasi Laravel

Langkah awal kita akan melakukan instalasi laravel menggunakan composer dengan perintah :

composer create-project laravel/laravel nama-aplikasi

 

Instalasi Package JWT

Selanjutnya lakukan instalasi package jwt untuk laravel menggunakan composer dengan perintah :

composer require tymon/jwt-auth

 

Konfigurasi Package JWT pada laravel

Buka file config/app.php pada laravel, pada bagian provider tambahkan baris berikut :

Tymon\JWTAuth\Providers\LaravelServiceProvider::class,

 

Lalu pada bagian Aliases tambahkan baris berikut :

'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class,

 

Lakukan publish package JWT dengan perintah :

php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"

 

Generate secret key untuk JWT dengan perintah :

php artisan jwt:secret

 

Lalu edit file app/User.php untuk Laravel 7 atau app/model/User.php untuk laravel 8 :

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
use 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',
];

public function getJWTIdentifier()
{
return $this-&gt;getKey();
}
public function getJWTCustomClaims()
{
return [];
}
}

 

Buat UserController dengan perintah :

php artisan make:controller UserController

 

Lakukan modifikasi pada app/Http/Controller/UserController.php menjadi :


<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;

class UserController extends Controller
{
public function login(Request $request)
{
$credentials = $request->only('email', 'password');

try {
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'invalid_credentials'], 400);
}
} catch (JWTException $e) {
return response()->json(['error' => 'could_not_create_token'], 500);
}

return response()->json(compact('token'));
}

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:6|confirmed',
]);

if($validator->fails()){
return response()->json($validator->errors()->toJson(), 400);
}

$user = User::create([
'name' => $request->get('name'),
'email' => $request->get('email'),
'password' => Hash::make($request->get('password')),
]);

$token = JWTAuth::fromUser($user);

return response()->json(compact('user','token'),201);
}

public function getAuthenticatedUser()
{
try {

if (! $user = JWTAuth::parseToken()->authenticate()) {
return response()->json(['user_not_found'], 404);
}

} catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {

return response()->json(['token_expired'], $e->getStatusCode());

} catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {

return response()->json(['token_invalid'], $e->getStatusCode());

} catch (Tymon\JWTAuth\Exceptions\JWTException $e) {

return response()->json(['token_absent'], $e->getStatusCode());

}

return response()->json(compact('user'));
}
}

Buat JWT Middleware dengan perintah :

php artisan make:middleware JwtMiddleware

 

Modifikasi file app/Http/Middleware/JwtMiddleware.php menjadi :


<?php

namespace App\Http\Middleware;

use Closure;
use JWTAuth;
use Exception;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;

class JwtMiddleware extends BaseMiddleware
{

/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
try {
$user = JWTAuth::parseToken()->authenticate();
} catch (Exception $e) {
if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException){
return response()->json(['status' => 'Token is Invalid']);
}else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException){
return response()->json(['status' => 'Token is Expired']);
}else{
return response()->json(['status' => 'Authorization Token not found']);
}
}
return $next($request);
}
}

Tambahkan JWT Middleware pada app/http/Kernel.php pada bagian routeMiddleware :

'jwt.verify' => \App\Http\Middleware\JwtMiddleware::class,

 

Buat route pada routes/api.php seperti berikut untuk laravel 8 :


Route::post('buat', [UserController::class, 'register']);
Route::post('login', [UserController::class, 'login']);
Route::get('book', [BookController::class, 'book']);

Route::get('barang', [BarangController::class, 'barangAuth'])->middleware('jwt.verify');
Route::get('user', [UserController::class, 'getAuthenticatedUser'])->middleware('jwt.verify');

Buat BarangController untuk melakukan testing pada autentikasi nya :

php artisan make:controller BarangController

 

Modifikasi BarangController menjadi :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;

class BarangController extends Controller
{
public function barang() {
$data = "Data Semua Barang";
return response()->json($data, 200);
}

public function barangAuth() {
$data = "Welcome " . Auth::user()->name;
return response()->json($data, 200);
}
}

Langkah terakhir lakukan testing pada setiap api yang kita buat dengan postman, untuk menjalankan gunakan perintah :

php artisan serve

 


Warning: Undefined variable $aria_req in /home/warungprogram/public_html/wp-content/themes/vikar/comments.php on line 51

Warning: Undefined variable $aria_req in /home/warungprogram/public_html/wp-content/themes/vikar/comments.php on line 56
*
*