Beast
Beast

Reputation: 426

How to use `fastapi_another_jwt_auth` in the middleware instead of via dependency injection in FastAPI?

I have a FastAPI project which uses fastapi_another_jwt_auth as a way of authenticating users. I'd intend to implement it in most of my endpoints except for a few whitelisted ones, but I find it hard to unit test endpoints that require authentication so I'm thinking of implementing it in a middleware with a simple if-else check for whitelisted endpoints. This way, I just need to disable the middleware to run unit tests and testing for authentication becomes trivial since we're just testing against a whitelist.

The API for fastapi_another_jwt_auth seems designed around the concept of Dependency Injection for FastAPI. Is there a way to use the same library in the middleware?

Upvotes: 2

Views: 973

Answers (1)

Beast
Beast

Reputation: 426

I looked at the code for fastapi_another_jwt_auth. Apparently, when injecting, the framework runs the AuthJWT constructor, which takes in the Request and Response object. This is shown below.

class AuthJWT(AuthConfig):
    def __init__(self,req: Request = None, res: Response = None):
        ...

Once it is successfully initialised, we can then use the .jwt_required() method.

So the way to implement it in the middleware is:

@app.middleware("http")
async def middleware_callback(req, call_next):
    if not whitelisted: # this is pseudocode
        auth = AuthJWT(req)
        auth.jwt_required() # throws error when user is not authenticated

    # rest of the logic
    ...

This way, I can manage all authentication at the middleware level and I don't have to inject the AuthJWT object into my view functions.

Upvotes: 2

Related Questions