【问题标题】:GraphQL - JWT -change payload of verifyToken mutation - djangoGraphQL - JWT - 更改 verifyToken 突变的有效负载 - django
【发布时间】:2020-11-15 08:42:22
【问题描述】:

我想更改 verifyToken 突变的有效负载。因此,我不想返回电子邮件,而是想返回 id 或整个对象

schema.py

import graphql_jwt
class Query(AccountsQuery, ObjectType):
    # This class will inherit from multiple Queries
    # as we begin to add more apps to our project
    pass

 
class Mutation( AccountsMutation, ObjectType):
    # This class will inherit from multiple Mutations 
    # as we begin to add more apps to our project
    token_auth = graphql_jwt.ObtainJSONWebToken.Field()
    verify_token = graphql_jwt.Verify.Field()
    refresh_token = graphql_jwt.Refresh.Field()
    pass  


schema = Schema(query=Query, mutation=Mutation) 

我看过这个:https://django-graphql-jwt.domake.io/en/latest/_modules/graphql_jwt/utils.html#get_user_by_natural_key

但我不知道如何实现 - 如果这是正确的方法

有什么想法可以做到吗?

【问题讨论】:

    标签: django graphql jwt token graphene-python


    【解决方案1】:

    要修改令牌的有效负载,您必须创建自定义jwt_payload 函数,并且必须将函数的路径添加到JWT_PAYLOAD_HANDLER 中的settings.GRAPHQL_JWT

    项目名称.settings.py

    GRAPHQL_JWT = {
        ...
        'JWT_PAYLOAD_HANDLER': 'polls.schema.jwt_payload',
        ...
    }
    

    polls.schema.py

    import graphql_jwt
    from datetime import datetime
    from projectname.settings import GRAPHQL_JWT
            
    def jwt_payload(user, context=None):
        username = user.get_username()
        
        payload = {
            user.USERNAME_FIELD: username,
            'user_id': user.id,
            'email': user.email,
            'phone': user.phone,
            'exp': datetime.utcnow() + GRAPHQL_JWT['JWT_EXPIRATION_DELTA'],
            ...    
        }
    

    original jwt payload function

    请注意,在您的情况下,user.USERNAME_FIELD 是您的电子邮件字段,它是您的有效负载中的默认字段(它也是您获取令牌所需的字段),您可以将其删除,也可以按照 @ 进行编辑987654322@,如果您声明自定义USERNAME_FIELD,您可以从“auth_user”表中的所有列中进行选择,但您必须在第一次运行python manage.py migrate 之前声明它

    【讨论】:

      猜你喜欢
      • 2020-03-22
      • 2016-05-29
      • 2017-02-11
      • 2021-07-09
      • 2016-03-12
      • 2020-09-13
      • 2019-10-29
      • 2021-04-20
      • 1970-01-01
      相关资源
      最近更新 更多