Laravel 11 & JWT (Json Web Token): Membuat Sistem Autentikasi Backend
Daftar isi
Pendahuluan
Hai! Hari ini kita akan mempelajari cara membuat otentikasi pada Laravel 11 API. Namun sebelum itu, mari kita bahas tentang API dan apa itu JSON Web Token (JWT).API adalah singkatan dari Application Programming Interface. API merupakan antarmuka yang memungkinkan aplikasi bertukar data. Secara sederhana, API adalah sekumpulan fungsi yang dapat digunakan oleh programmer untuk membangun perangkat lunak dan aplikasi.
JWT adalah singkatan dari JSON Web Token. Ini adalah standar terbuka (RFC 7519) yang mendefinisikan cara yang ringkas dan mandiri untuk mentransmisikan informasi antar pihak dengan aman dalam bentuk objek JSON. JWT umumnya digunakan untuk otorisasi, pertukaran informasi, dan lain-lain.
Jika kesulitan dalam mengikuti tutorial di artikel ini, silahkan tonton video youtube Kami.
Tutorial Video
Persyaratan Instalasi
- Composer
- PHP Versi >= 8.2
Langkah 1: Install Laravel 11
Instal melalui composer:
composer create-project laravel/laravel laravel-11-jwt
Langkah 2: Atur Konfigurasi Basis Data
Buka file .env dan atur konfigurasi database:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=nama database Anda(laravel_11_jwt)
DB_USERNAME=username database Anda(root)
DB_PASSWORD=password database Anda(root)
Langkah 3: Aktifkan API dan Perbarui Pengecualian Otentikasi
Secara default, rute API laravel 11 tidak diaktifkan di laravel 11. Kami akan mengaktifkan API:
php artisan install:api
Setelah mengaktifkan API, kami sekarang akan memperbarui file bootstrap/app.php untuk pengecualian otentikasi middleware API sehingga tidak akan dialihkan ke login tetapi akan memunculkan pengecualian:<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Request;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
//
})
->withExceptions(function (Exceptions $exceptions) {
$exceptions->render(function (AuthenticationException $e, Request $request) {
if ($request->is('api/*')) {
return response()->json([
'message' => $e->getMessage(),
], 401);
}
});
})->create();
Langkah 4: Instal dan Siapkan paket JWT Auth
Jalankan perintah berikut untuk menginstal versi terbaru:
composer require php-open-source-saver/jwt-auth
publikasikan file konfigurasi paket:
php artisan vendor:publish --provider="PHPOpenSourceSaver\JWTAuth\Providers\LaravelServiceProvider"
menghasilkan kunci rahasia. Ini akan menambahkan nilai konfigurasi JWT pada .env file:
php artisan jwt:secret
perbarui konfigurasi penjaga autentikasi pada file config/auth.php.
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
Langkah 5: Perbarui Model Pengguna
Terapkan terlebih dahulu kontrak Tymon\JWTAuth\Contracts\JWTSubject pada Model Pengguna dan implementasikan metode getJWTIdentifier() dan getJWTCustomClaims() pada file app/Models/User.php:
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use PHPOpenSourceSaver\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
/**
* 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 [];
}
}
Langkah 6: Buat StoreUserRequest
Buat request StoreUserRequest dengan perintah ini:
php artisan make:request StoreUserRequest
Kemudian buka file app/Http/Request/StoreUserRequest.php dan tambahkan kode ini:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreUserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users,email',
'password' => 'required|string|confirmed|min:8',
];
}
}
Langkah 7: LoginRequest
Buat request LoginRequest dengan perintah ini:
php artisan make:request LoginRequest
Kemudian buka file app/Http/Request/LoginRequest.php dan tambahkan kode ini:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class LoginRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'email' => 'required|email',
'password' => 'required',
];
}
}
Langkah 8: Buat AuthController
Buat pengontrol menggunakan perintah ini:
php artisan make:controller AuthController
Kemudian buka file app/Http/Controllers/AuthController.php dan tambahkan kode-kode ini:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Requests\LoginRequest;
use App\Http\Requests\StoreUserRequest;
use App\Models\User;
use Illuminate\Support\Facades\Request;
class AuthController extends Controller
{
/**
* Register a User.
*
* @return \Illuminate\Http\JsonResponse
*/
public function register(StoreUserRequest $request)
{
try {
$user = new User;
$user->name = $request->name;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->save();
return response()->json($user, 201);
} catch (\Exception $e) {
return response()->json(['error' => 'Failed to create user'], 500);
}
}
/**
* Get a JWT via given credentials.
*
* @return \Illuminate\Http\JsonResponse
*/
public function login(LoginRequest $request)
{
$credentials = $request->only('email', 'password');
if (!$token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Invalid email or password.'], 401);
}
return $this->respondWithToken($token);
}
/**
* Get the authenticated User.
*
* @return \Illuminate\Http\JsonResponse
*/
public function me()
{
return response()->json(auth()->user());
}
/**
* Log the user out (Invalidate the token).
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout()
{
auth()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
/**
* Refresh a token.
*
* @return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken(auth()->refresh());
}
/**
* Get the token array structure.
*
* @param string $token
*
* @return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60
]);
}
}
Langkah 9: Daftarkan Rute
lalu daftarkan rute di rute/api.php, rute dengan middleware auth:api memeriksa apakah pengguna diautentikasi sebelum permintaan dapat dilanjutkan.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
Route::group([
'middleware' => 'api',
'prefix' => 'auth'
], function ($router) {
Route::post('/register', [AuthController::class, 'register'])->name('register');
Route::post('/login', [AuthController::class, 'login'])->name('login');
Route::post('/logout', [AuthController::class, 'logout'])->middleware('auth:api')->name('logout');
Route::post('/refresh', [AuthController::class, 'refresh'])->middleware('auth:api')->name('refresh');
Route::post('/me', [AuthController::class, 'me'])->middleware('auth:api')->name('me');
});
Langkah 10: Jalankan Aplikasi
Jalankan aplikasi laravel:
php artisan serve
Posting Komentar untuk "Laravel 11 & JWT (Json Web Token): Membuat Sistem Autentikasi Backend"
Posting Komentar
Silahkan komentar dengan bijak jika ada yang ingin ditanyakan.