获取 AttributeError: 'str' 对象在 rest_framework_simplejwt.serializers.TokenObtainPairSerializer.get_token() 中没有属性 'decode'

问题描述

我正在开发与选举相关的网络应用程序,并尝试使用 rest_framework_simplejwt.serializers 实现授权令牌概念,在运行此代码时,我遇到了与 str 类相关的错误,如下所示: AttributeError: 'str' object has no attribute 'decode' 从这部分代码data['refresh'] = str(refresh)

class AuthTokenObtainSerializer(TokenObtainPairserializer):
    """
    Seializer for th user authentication object.

    Returns
    -------
        json: 'access' and 'token'
    """
    default_error_messages = {
        'no_active_account': _('No active account found with the given credentials')  # noqa: E501
    }

    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.fields['password'] = serializers.CharField(
            style={'input_type': 'password'},trim_whitespace=False
        )
        self.fields['face_image'] = serializers.ImageField()

    def validate(self,attrs):
        """
        Validates and authenticate the user.
        """
        citizenship_number = attrs.get('citizenship_number')
        password = attrs.get('password')
        face_image = attrs.get('face_image')

        face_id = FaceIdAuthBackend()
        user = face_id.authenticate(
            citizenship_number=citizenship_number,password=password,face_id=face_image
        )

        if user is None or not user.is_active:
            raise exceptions.AuthenticationFailed(
                self.error_messages['no_active_account'],'no_active_account',)

        update_last_login(None,user)

        data = {}
        refresh = self.get_token(user)

        data['refresh'] = str(refresh)

        data['access'] = str(refresh.access_token)

        return data

请帮我解决这个......

解决方法

当我在不同来源寻找解决方案时,我知道这个特定问题来自 PyJWT 包的最新版本,所以我必须将其降级到 v1.7.1,现在我不再遇到这个问题了。

来源:https://github.com/jazzband/django-rest-framework-simplejwt/issues/346