Skip to content

Authentication Middleware Refactor #145

Closed
@AntonioMrtz

Description

@AntonioMrtz

Description

This issue aims to refactor the existing Authentication Middleware located in our backend API. In the process we will want to rename the middleware to be more significative and improve exception handling to unexpected errors.

Context

Current authentication Middleware is named CheckJwtAuthMiddleware. It serve its purpouse in the early stages of auth in the app but time has come from it to have a more significative name. See CheckJwtAuthMiddleware.

Furthermore, we want to improve the unexpected exceptions that we can have in our app ( although they shouldnt exists ). Our current implementation of the dispatch method does the following:

  1. Intercepts any incoming HTTP Requests into the API.
  2. Decides wheter or not they should be blocked or bypassed depending on endpoint security and JWT Token provided.
  3. call_next method redirects the HTTP Request into our endpoints.
  4. If an unhandled exception is raised during call_next the try except block will be trigger ( line 85 ) and a response with 401 Unauthorized will be sent into the client.

imagen

imagen

The objective is to make exception handling more precise. Its not correct to return 401 code if an unexpected error non related to authentication happens. As you can see theres code duplication and the code execution flow can be improved.

How to do it

  • Rename CheckJwtAuthMiddleware to JwtAuthMiddleware
  • Improve code execution flow. Delete duplicate code and improve legibility and clearness. Update modified method docs and logging messages if needed.
# Expected code execution flow

1. Check if the request has to be bypassed ( already done ). If has to be bypassed use `call_next`.
2. If not bypassed extract JWT token from the request and validate it.
3. If non valid return raise `JWTValidationException`.
4. If valid continue execution flow using `call_next`.
5. Handle exceptions correctly inside dispatch block. Differentiate Auth Exceptions from unhandled ones from `call_next` methods. Use 401 or 500 depending on the exception and log the process.

Testing

  • All tests keep passing.
  • Mock health endpoint, so it returns an exception and check that were processing it correctly and returning 500 HTTP error.

Metadata

Metadata

Assignees

Labels

backendBackend related issuesgood first issueGood for newcomershelp-wantedHelp is wantedpythonPull requests that update Python coderefactorCode changes or improvements that do not change code behaviour

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions