How to create an authentication middleware to validate tokens in Phalcon? #16806
Jose12Abel
started this conversation in
General
Replies: 1 comment 1 reply
-
Have a look at this repository: https://github.com/phalcon/rest-api |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hello community,
I'm developing a REST API using the Phalcon framework (version X.X) and need to implement a security layer to protect my endpoints.
My goal:
I want the request to be intercepted before any action logic is executed in my controllers to validate an authentication token (e.g., a JWT) sent in the headers (Authorization: Bearer ).
If the token is valid, the request should continue to the requested endpoint. If the token is invalid, nonexistent, or has expired, the system should stop execution and return an error response (e.g., a 401 Unauthorized) automatically, without the controller code having to perform this validation.
What I've researched:
I've read that this can be achieved in Phalcon in several ways, but I'm not sure which is the "best practice" or the most efficient and maintainable. My ideas are:
EventsManager
: Listen to thedispatcher:beforeExecuteRoute
event to execute my token validation logic before the route is dispatched to the controller.BaseController
and put the validation logic in itsinitialize()
method. However, this would force me to always inherit from this controller, and it doesn't seem that decoupled.My question is:
What is the recommended and most robust way to implement this global authentication filter in Phalcon? Is it through the EventsManager or by creating a Middleware class?
It would be very helpful if you could provide a basic example of how to structure this code. For example:
I want to avoid having to add this to every action:
Beta Was this translation helpful? Give feedback.
All reactions