[英]Django Graphql middleware decode token
In my project I used Django
and GraphQl
for building API. User will be authenticated by API Gateway
in AWS
, and send a JWT token
, with uuid username
body, included in the request headers to the backend.在我的项目中,我使用
Django
和GraphQl
来构建 API。用户将通过AWS
中的API Gateway
进行身份验证,并发送一个JWT token
,带有 uuid username
正文,包含在请求标头中到后端。
I need to decode that token and get an username
value, that will be next used in the resolvers.我需要解码该令牌并获取
username
值,接下来将在解析器中使用。 I have planned to use something similar as G
object in Flask
or something similar using Rack Djangos middleware but I'm struggling how to do it in Django.我计划在
Flask
中使用类似于G
object 的东西或使用 Rack Djangos 中间件的类似东西,但我正在努力如何在 Django 中做到这一点。
Do you have any idea or hint?你有什么想法或提示吗?
Here's the result which I implemented:这是我实施的结果:
The middleware checks the jwt token before resolver call, based on decoded username it create a User instance, that is assigned in info.context.user parameter.中间件在解析器调用之前检查 jwt 令牌,基于解码的用户名,它创建一个 User 实例,该实例在 info.context.user 参数中分配。 The info.context will be visible in resolver.
info.context 将在解析器中可见。
So basically in resolver you can check a User instance as:所以基本上在解析器中你可以检查一个用户实例:
user = info.context.user
if isinstance(user, User):
# do something
middleware.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: str
utils.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',)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.