We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Phalcon JWT best practices


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:

if (!isset($headers["Authorization"]) || empty($headers["Authorization"])) {
        //devolvemos un 403, Forbidden
        $response->setStatusCode(403, "Forbidden");

    $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());

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 or beforeExecuteRoute is the right thing to do. I personally prefer beforeExecuteRoute because JWT::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:




Cheers !


Thank you, i will look into it!