Phalcon JWT best practices
Hello.
I was wondering how you guys have implementet JWT in your application. The way i have done it, is by adding a beforeDispatch, that runs this code:
<?php
if (!isset($headers["Authorization"]) || empty($headers["Authorization"])) {
//devolvemos un 403, Forbidden
$response->setStatusCode(403, "Forbidden");
$response->send();
die();
}
$token = explode(" ", $headers["Authorization"]);
$token = trim($token[1], '"');
try {
JWT::$leeway = 60; // 60 seconds
$user = JWT::decode($token, $this->jwt_key, array('HS256'));
} catch (\Firebase\JWT\ExpiredException $e) {
$response->setStatusCode(405, $e->getMessage());
$response->send();
die();
}
This code is implemented in my module, as an event.
My question is, what is the best way to setup JWT for phalcon, maybe you have done this in a much smarter way?
Using
beforeDispatch
,beforeDispatchLoop
orbeforeExecuteRoute
is the right thing to do. I personally preferbeforeExecuteRoute
becauseJWT::decode()
(or any other unnecessary checks) won't be executed if the action doesn't exists - but that depends on your setup and if you use or not the ACL for protecting an entire enpoint or just some actions. If you want to go wild or need a more complex setup, you can use it in combination with the Events Manager (https://docs.phalcon.io/4.0/en/events) .The most important thing is how you design your API. Here are some nice articles:
https://docs.microsoft.com/en-us/azure/architecture/best-practices/api-design
https://hackernoon.com/restful-api-designing-guidelines-the-best-practices-60e1d954e7c9
Cheers !
From: https://forum.phalcon.io/discussion/20279/phalcon-jwt-best-practices