We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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:

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?



51.1k
Accepted
answer

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:

https://docs.microsoft.com/en-us/azure/architecture/best-practices/api-design

https://florimond.dev/blog/articles/2018/08/restful-api-design-13-best-practices-to-make-your-users-happy/

https://hackernoon.com/restful-api-designing-guidelines-the-best-practices-60e1d954e7c9

Cheers !



2.4k

Thank you, i will look into it!