在我的项目中,我使用了Django和GraphQl来构建API。用户将通过AWS中的API Gateway进行鉴权,并将请求头部中包含uuid username body的JWT token发送到后台。
我需要解码该令牌并获得一个username值,该值将在解析器中使用。我计划在Flask中使用类似于G对象的东西,或者使用Rack Djangos middleware来使用类似的东西,但我正在努力在Django中如何做到这一点。
你有什么想法或提示吗?
发布于 2020-12-01 15:19:18
下面是我实现的结果:
中间件在解析器调用前检查JWT令牌,根据解码后的用户名创建一个用户实例,该实例在info.context.user参数中赋值。info.context将在解析程序中可见。
因此,基本上在解析器中,您可以检查用户实例,如下所示:
user = info.context.user
if isinstance(user, User):
# do somethingmiddleware.py
class AuthorizationGraphQLMiddleware:
"""Middleware add User object for each GraphQL resolver info.context"""
def resolve(self, next, root, info, **kwargs):
username = None
auth_header = info.context.META.get('HTTP_AUTHORIZATION')
if auth_header:
username = decode_token(auth_header)['username']
if username is not None:
info.context.user = User(username)
else:
info.context.user = AnonymousUser()
return next(root, info, **kwargs)entities.py
@dataclass
class User:
name: strutils.py
class TokenValidationError(GraphQLError):
pass
def decode_token(token):
try:
return jwt.decode(token.replace('Bearer ', ''), verify=False)
except (jwt.DecodeError, AttributeError):
raise TokenValidationError('Invalid token.')settings.py
GRAPHENE = {
'MIDDLEWARE': ('api.graphql.middleware.AuthorizationGraphQLMiddleware',)
}https://stackoverflow.com/questions/63686801
复制相似问题