首页 > 解决方案 > 我们可以将 Django GraphQL JWT 用于身份验证,还可以将 Django REST 框架用于其他 API 吗?

问题描述

  1. 我觉得很难涵盖 DRF_jwt/DRF_oauth2 但 Django GraphQL JWT 似乎很容易......
  2. 为了方便起见,我可以同时使用它们吗
  3. 我是 Rest Framework 的新手

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

解决方案


您可以为DRF创建一个自定义身份验证后端,该后端扩展rest_framework.authentication.BaseAuthentication并用于以完全相同的方式在DRFgraphql_jwt.utils中对用户进行身份验证。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

推荐阅读