[Question] Add middleware to GraphQLApp
See original GitHub issueI’m wondering if it’s possible to add middlewares to a GraphQLApp
directly, for example is it possible to add authentication on top of it?
I think I could make it work using the following strategy, but is there a better way?
def authentication_check(func):
async def check(*args, **kwargs):
print("We could check for authentication here")
response = await func(*args, **kwargs)
print("...")
return response
return check
graphql_app = GraphQLApp(schema=schema, executor_class=AsyncioExecutor)
graphql_app.handle_graphql = authentication_check(graphql_app.handle_graphql)
Maybe it would be better to intercept calls to graphql_app.execute
so we can decide which request are allowed depending on the kind of user? Or, as suggested in graphene documentation we could just allow to add middleware directly to schema.execute
right here.
async def execute( # type: ignore
self, query, variables=None, context=None, operation_name=None, middleware=None
):
return await self.schema.execute(query, middleware=middleware, ...)
Or maybe even better, allow the user to pass any parameter to schema.execute
:
async def execute( # type: ignore
self, query, **optional_args
):
return await self.schema.execute(query, **optional_args)
I found this location to add a middleware very strange (adding it on the schema directly would make more sense to me), but if that’s what graphene does I guess that’s the better way? I’m very new to this so maybe I’m just lost ^^.
Issue Analytics
- State:
- Created 4 years ago
- Reactions:1
- Comments:9 (2 by maintainers)
Top GitHub Comments
Here’s what I did, in case anyone finds it useful (or has a better suggestion). I derived my own app from
GraphQLApp
, and re-implementedexecute
to inject the middleware.I’m still investigating this, but another (probably better) option to check for authorization is what I suggested in the original question: Modify the graphQL schema on the flight to add a middlewares directly to
schema.execute
:This way we can access to parsed graphQL queries, which allows us to get more accurate information faster. For example we just need to search a list to check things like
'customersList' in info.path
.Here is another example limiting the maximum query depth (like some people tend to do):
This also have the benefit or returning meaningful results to the client:
That would be pretty easy to update starlette to allow for such middleware to be passed directly to
GraphQLApp
.Edit I noticed I should probably use Starlette’s scopes for user groups authorizations, but that’s rather not clear to me. It would only require to update the code like this:
And have credentials adding user groups like so:
AuthCredentials(["authenticated", authorization_group])
.