简体   繁体   English

Django Graphql 中间件解码令牌

[英]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.在我的项目中,我使用DjangoGraphQl来构建 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.

相关问题 "创建新中间件后,无法使用 JWT 令牌在 Django Rest Framework 自定义请求中间件中使用用户" - Cannot use User in Django Rest Framework Custom Request middleware using JWT token after created new middleware 如何解码和验证 simple-jwt-django-rest-framework 令牌 - How to decode and verify simple-jwt-django-rest-framework token 如何使用 django-graphql-social-auth 库获取刷新令牌 - How to get the Refresh Token with the django-graphql-social-auth library Django中间件 - Django Middleware Access Token 和 Refresh Token 的默认到期时间是多少? (Django GraphQL JWT) - What are the default expiry time for Access Token and Refresh Token? (Django GraphQL JWT) CSRF 中间件令牌丢失? - CSRF middleware token missing? 带有自定义中间件的django自定义身份验证后端(用户名,密码和令牌不使用身份验证) - django custom authentication backend with custom middleware (both username,password and token absed auth) 单令牌刷新与长时间运行的刷新令牌(Django GraphQL JWT) - Single token refresh vs Long running refresh tokens (Django GraphQL JWT) 如何使用 python-social-auth 和 django-graphql-auth 返回刷新令牌? - How can I return the refresh token using python-social-auth and django-graphql-auth? DJANGO-GRAPHQL-JWT:我们如何知道刷新令牌发布后的时间? - DJANGO-GRAPHQL-JWT: How do we know how old is the refresh token after it has been issued?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM