Python 有没有一种方法可以使用Graphene/GraphQL从GraphQLString解析AST
我希望使用Python 有没有一种方法可以使用Graphene/GraphQL从GraphQLString解析AST,python,django,graphql,graphene-python,pyjwt,Python,Django,Graphql,Graphene Python,Pyjwt,我希望使用PyJWT为我的GraphQL端点编写一个自定义中间件。问题是我不想保护我的登录。所以我试图编写中间件来排除登录变异 编写GraphQL中间件很容易做到这一点,因为传递给中间件的参数使我能够检查查询的名称 class JWTMiddleware(object): def resolve(self, next, root, info, **args): if info.field_name == 'login': return next(r
PyJWT
为我的GraphQL端点编写一个自定义中间件。问题是我不想保护我的登录。所以我试图编写中间件来排除登录变异
编写GraphQL中间件很容易做到这一点,因为传递给中间件的参数使我能够检查查询的名称
class JWTMiddleware(object):
def resolve(self, next, root, info, **args):
if info.field_name == 'login':
return next(root, info, **args
# rest of auth logic
但由于GraphQL总是返回200
,因此我不能将状态代码用作客户端的身份验证失败检查。并且必须检查错误
数组,以查看消息是未经授权的
还是什么
错误响应示例:
{
errors: [
{
message: 'Unauthorized: JWT invalid',
...,
},
...
],
data: null
}
这很好,但我更愿意使用响应的状态代码作为检查,因此我决定使用自定义装饰器包装GraphQL视图
def jwt_required(fn):
def wrapper(request):
# no access to query name, just the GraphQLString
# need function to parse the AST of a GraphQLString
graphql_string = request.body.decode('utf-8')
query_name = ast[0].name # or something like this
if query_name == 'login':
return fn(request)
# rest of auth logic
return fn(request)
return wrapper
def protected_graphql_view():
return jwt_required(GraphQLView.as_view())
urlpatterns = [
path('admin/', admin.site.urls),
path('graphiql', GraphQLView.as_view(graphiql=True)),
path('graphql', protected_graphql_view()),
path('token/refresh', refresh_token_view),
]
通过这样做,我现在可以返回带有不同状态代码的响应。但问题是,除非我能正确解析GraphQLString,否则我无法轻松检查请求是否用于登录并跳过auth逻辑
如果可能的话,我不想定制一些东西。我想GraphQL或石墨烯会提供类似的东西
如果我需要提供更多信息,请告诉我。谢谢你的帮助 我建议您以不同的方式解决这个问题,并使用两个不同的API端点。将登录名和其他您不希望中间件用于的内容放在第二个变体中。详细内容请参见此答案。我喜欢这个想法。我要试一试。