【问题标题】:Can we Use Django GraphQL JWT For authentification and also Django rest framework for other apis together?我们可以将 Django GraphQL JWT 用于身份验证,还可以将 Django REST 框架用于其他 API 吗?
【发布时间】:2020-04-07 18:54:33
【问题描述】:
  1. 我觉得很难涵盖 DRF_jwt/DRF_oauth2 但是 Django GraphQL JWT 看起来很简单....
  2. 我可以同时使用它们以方便我吗
  3. 我是 Rest Framework 的新手

【问题讨论】:

    标签: django-rest-framework django-rest-framework-jwt


    【解决方案1】:

    如果您的意思是使用 django-graphql-jwt 进行身份验证并使用 DRF 进行其他用户帐户相关操作,例如更新、检索、删除、重置密码...

    您可以使用django-graphql-auth

    它扩展了 django-graphql-jwt,并提供了一个完整的 api 来处理用户帐户。

    【讨论】:

      【解决方案2】:

      您可以为 DRF 创建自定义身份验证后端,该后端扩展 rest_framework.authentication.BaseAuthentication 并使用 graphql_jwt.utilsDRF 中对用户进行身份验证,方式与 django-graphql-jwt 完全相同它。

      这就是我所拥有的:

      from graphql_jwt.exceptions import JSONWebTokenError
      from graphql_jwt.utils import get_payload, get_user_by_payload
      from rest_framework.authentication import BaseAuthentication, get_authorization_header
      from rest_framework import exceptions
      
      
      class TokenAuthentication(BaseAuthentication):
          keyword = 'JWT'
      
          def authenticate(self, request):
              auth = get_authorization_header(request).split()
      
              if not auth or auth[0].lower() != self.keyword.lower().encode():
                  return None
      
              if len(auth) == 1:
                  msg = 'Invalid token header. No credentials provided.'
                  raise exceptions.AuthenticationFailed(msg)
              elif len(auth) > 2:
                  msg = 'Invalid token header. Token string should not contain spaces.'
                  raise exceptions.AuthenticationFailed(msg)
      
              try:
                  token = auth[1].decode()
              except UnicodeError:
                  msg = 'Invalid token header. Token string should not contain invalid characters.'
                  raise exceptions.AuthenticationFailed(msg)
      
              try:
                  payload = get_payload(token)
                  user = get_user_by_payload(payload)
              except JSONWebTokenError as e:
                  raise exceptions.AuthenticationFailed(str(e))
      
              if user is None or not user.is_active:
                  raise exceptions.AuthenticationFailed('User inactive or deleted.')
      
              return (user, None)
      
          def authenticate_header(self, request):
              return self.keyword
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-01
        • 2021-12-21
        • 2019-07-11
        • 2019-05-02
        • 2017-12-07
        • 2018-10-17
        • 2016-12-25
        • 2014-08-12
        相关资源
        最近更新 更多