在调用decode()函数时,需要传入"algorithms"参数的值。

13
以下页面是项目代码: 如果我使用 token = jwt.encode(payload,'secret', algorithm='HS256').decode('utf-8') 这个语句,那么就会出现

'str' object has no attribute 'decode'

错误。同时,如果我将它移除并在没有使用 .decode('utf-8') 的情况下继续进行后续的代码时,它可以正常工作。但是,当我应用 payload = jwt.decode(token, 'secret', algorithm=['HS256']) 时,
则会出现

调用 decode() 时需要传递“algorithms”参数的值

以上述错误提示为例,我的问题是在调用decode()时需要传递“algorithms”参数的值,请帮我纠正这个错误。
查看页面:
from django.http import request, response
from django.shortcuts import render
from rest_framework import serializers
from rest_framework.views import APIView
from myusers.serializers import UserSerializer
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.response import Response
from .models import User
import jwt, datetime
# Create your views here.
class RegisterView(APIView):
    def post(self,request):
        serializer = UserSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

class LoginView(APIView):
       def post(self,request):
           email=request.data['email']
           password = request.data['password']

           user = User.objects.filter(email=email).first()

           if user is None:
               raise AuthenticationFailed('User Not Found!!!')
            
           if not user.check_password(password):
               raise AuthenticationFailed('Incorrect Password!!!')
           
           payload={
               'id':user.id,
               'exp':datetime.datetime.utcnow() + datetime.timedelta(minutes=60),
               'iat':datetime.datetime.utcnow()
           }

           token = jwt.encode(payload,'secret', algorithm='HS256').decode('utf-8')

           response = Response()
           
           response.data={
                   "jwt":token
               }
             
           response.set_cookie(key='jwt', value=token, httponly=True)
           return response

class Userview(APIView):
    def get(self,request):
        token = request.COOKIES.get('jwt')
        
        if not token:
            raise AuthenticationFailed('User Authentication Failed!!!')
        
        try:
            payload = jwt.decode(token, 'secret', algorithm=['HS256'])
        except jwt.ExpiredSignatureError:
            raise AuthenticationFailed('Unauthenticated!')
        
        user = User.objects.filter(id = payload['id']).first()
        serializer = UserSerializer(user)
        return Response(serializer.data)


class LogoutView(APIView):
    def post(self, request):
        response = Response()
        response.delete_cookie('jwt')
        response.data = {
            'message': 'success'
        }
        return response


Serializer Page:
from django.db.models import fields
from rest_framework import serializers
from .models import User
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'name','email','password']
        extra_kwargs={
            'password' : {'write_only':True}
        }
    
    def create(self, validated_data):
        password = validated_data.pop('password',None)
        instance = self.Meta.model(**validated_data)

        if password is not None:
            instance.set_password(password)
        instance.save()
        return instance

Model Page: 
from django.db import models
from django.contrib.auth.models import AbstractUser

# Create your models here.
class User(AbstractUser):
    name = models.CharField(max_length=255)
    email = models.CharField(max_length=250, unique=True)
    password = models.CharField(max_length=255)
    username = None

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    
Urls page:
from django.urls import path
from .views import RegisterView, LoginView, Userview

urlpatterns = [
    path('register',RegisterView.as_view()),
    path('login',LoginView.as_view()),
    path('user',Userview.as_view()),
    path('logout',Userview.as_view()),
]


Setting Page:
"""
Django settings for login project.

Generated by 'django-admin startproject' using Django 4.0.1.

For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-k02ug7k7bm-q0cgy4uini(mol=__ye-cm)$c1q+utmhg86ds$7'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myusers',
    'rest_framework',
    'corsheaders'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'login.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'login.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = 'static/'
AUTH_USER_MODEL = 'myusers.User'

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'


CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
3个回答

36

您缺少一个 's',在decode函数中参数应该叫做“algorithms”:

payload = jwt.decode(token, 'secret', algorithms=['HS256'])

而且您还要传递一个可能值的数组。

调用encode时,参数是“algorithm”,并且只有一个单一的值。

原因是在编码(即签名)期间,您必须明确使用一个算法,因为令牌只能使用一个算法进行签名。但在解码(验证)期间,您告诉函数您接受哪些算法。


3
标准库中的这种花里胡哨的东西就是开发人员永远会因维护而得到报酬的原因...曾经测试了数月并且工作了一年之久的代码,因为这些垃圾东西突然停止工作。我会称其为职业防御... - Vityata
谢谢,它对我有用。但是当我在Linux(Ubuntu)中执行jwt.decode(token,'secret',algorithm = ['HS256'])时,它对我有效。我最终在Windows中遇到了这个问题。有什么想法为什么会这样吗? - TheLazy
1
@TheLazy 也许是simplejwt的不同版本? - jps
@jps,刚刚检查了版本并发现了差异。无论如何还是谢谢你。 - TheLazy
1
@Vityata 我完全同意你的观点。API不应该将可选参数变成必填项,永远都不应该这样做。它们应该在保持向后兼容性的同时处理它们的花哨把戏... - jpmartineau

3

我不得不传递verify=False,options={'verify_signature': False}才能使其正常工作。


这对我也起作用了。我不知道不验证签名是好还是坏,但至少当升级遗留软件的Python版本时,我不再被困住了。 - Johan
这对我也起作用了。我不知道不验证签名是好是坏,但至少当升级一个遗留软件的Python版本时,我不再卡住了。 - undefined

1
另一个解决方案是将 PyJWT 版本降级到 1.7.1,这样您就不需要传递 "algorithms" 参数。

像这样:

jwt.decode(encoded, verify=False)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接