Tutorial Codeigniter 4 - Restful API JWT Authentication (user loggedin with token access)
1. Install JWT Package dengan composer dalam terminal cmd;
composer require firebase/php-jwt
2. Updatge file .env dengan memasukkan kod secret key jwt;
#--------------------------------------------------------------------
# JWT
#--------------------------------------------------------------------
JWT_SECRET = 'SECRET KEY FOR JWT'
CONTROLLER
1. Buat controller untuk Login dan User (ini untuk dashboard) dengan terminal cmd;
php spark make:controller Login
php spark make:controller User
2. Buka file app/Controllers/Login.php dan update kod;
class Login extends BaseController
{
use ResponseTrait;
public function index()
{
$userModel = new UserModel();
$email = $this->request->getVar('email');
$password = $this->request->getVar('password');
$user = $userModel->where('email', $email)->first();
if (is_null($user)) {
return $this->respond([
'error' => 'Invalid username or password',
], 401);
}
$pwd_verify = password_verify($password, $user['password']);
if (!$pwd_verify) {
return $this->respond([
'error' => 'Invalid username or password',
], 401);
}
$key = getenv('JWT_SECRET');
$iat = time();
$exp = $iat + 3600;
$payload = array(
"iss" => "Issuer of the JWT",
"aud" => "Audience that the JWT",
"sub" => "Subject of the JWT",
"iat" => $iat, // time the JWT issued at
"exp" => $exp, // Expiration time of token
"email" => $user['email'],
);
$token = JWT::encode($payload, $key, 'HS256');
$response = [
'message' => 'Login success!',
'token' => $token,
];
return $this->respond($response, 200);
}
}
3. Buka file app/Controllers/User.php dan update kod;
class User extends BaseController
{
use ResponseTrait;
public function index()
{
$users = new UserModel();
return $this->respond([
'users' => $users->findAll()
], 200);
}
}
CONTROLLER FILTER
1. Jalankan arahan di bawah dengan terminal cmd untuk membuat Filter baru;
php spark make:filter AuthFilter
2. Buka file app/Filters/AuthFilter.php dan update kod;
class AuthFilter implements FilterInterface
{
/**
* Do whatever processing this filter needs to do.
* By default it should not return anything during
* normal execution. However, when an abnormal state
* is found, it should return an instance of
* CodeIgniter\HTTP\Response. If it does, script
* execution will end and that Response will be
* sent back to the client, allowing for error pages,
* redirects, etc.
*
* @param RequestInterface $request
* @param array|null $arguments
*
* @return RequestInterface|ResponseInterface|string|void
*/
public function before(RequestInterface $request, $arguments = null)
{
$key = getenv('JWT_SECRET');
$header = $request->getHeaderLine("Authorization");
$token = null;
// extract the token from the header
if(!empty($header)) {
if (preg_match('/Bearer\s(\S+)/', $header, $matches)) {
$token = $matches[1];
}
}
// check if token is null or empty
if(is_null($token) || empty($token)) {
$response = service('response');
$response->setBody('Access denied');
$response->setStatusCode(401);
return $response;
}
try {
// $decoded = JWT::decode($token, $key, array("HS256"));
$decoded = JWT::decode($token, new Key($key, 'HS256'));
} catch (Exception $ex) {
$response = service('response');
$response->setBody('Access denied');
$response->setStatusCode(401);
return $response;
}
}
/**
* Allows After filters to inspect and modify the response
* object as needed. This method does not allow any way
* to stop execution of other after filters, short of
* throwing an Exception or Error.
*
* @param RequestInterface $request
* @param ResponseInterface $response
* @param array|null $arguments
*
* @return ResponseInterface|void
*/
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
//
}
}
3. Kemudian buka file app/Config/Filters.php dan update kod;
public array $aliases = [
'csrf' => CSRF::class,
'toolbar' => DebugToolbar::class,
'honeypot' => Honeypot::class,
'invalidchars' => InvalidChars::class,
'secureheaders' => SecureHeaders::class,
'cors' => Cors::class,
'forcehttps' => ForceHTTPS::class,
'pagecache' => PageCache::class,
'performance' => PerformanceMetrics::class,
'authFilter' => \App\Filters\AuthFilter::class, <-- update
];
ROUTES
1. Buka file app/Config/Routes.php dan update kod;
$routes->group("apis", function($routes) {
$routes->post("register", "Register::index");
$routes->post("login", "Login::index");
$routes->get("users", "User::index", ['filter' => 'authFilter']);
});
2. Save dan run menggunakan HTTPie.
- URL: https://example.com/project1/apis/login
Form Body:
email: admin@mail.com
password: admin12345
Copy TOKEN dan buka URL: https://example.com/project1/apis/users dan PASTE TOKEN tadi pada Auth Bearer Token.
Jika berhasil Response 200 akan keluar dan data user seperti dalam gambar di atas akan terlihat dan jika terdapat kesalahan pada token atau token yang digunakan sudah expired date maka Response 401 seperti gambar di bawah akan tertera.
Comments
Post a Comment