调用 decode() 时,需要为 "algorithms" 参数传入一个值



以下页面是项目的代码:如果我使用token = jwt.encode(payload,'secret', algorithm='HS256').decode('utf-8')语句然后

"r"对象没有属性"解码">

错误正在发生。此外,当我在没有.decode('utf-8')的情况下删除和使用它并继续执行下一个代码时。它运行良好。但当我应用payload = jwt.decode(token, 'secret', algorithm=['HS256'])

然后

需要为";算法";当调用decode((时的自变量";

出现上述错误。请帮我纠正这个错误。这就是上面提到的错误,即调用decode((错误时说算法参数应该被纠正。

查看页面:

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

您缺少一个"s",该参数被称为"算法";在解码功能中:

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

并且还传递了一个可能值的数组。

当您调用encode时,参数为";算法";并且仅取单个值。

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

我必须通过verify=False,options={'verify_signature':False}以便使其工作。

另一个解决方案是将PyJWT版本降级到1.7.1,因此您不需要通过;算法";论点

像这样:

jwt.decode(encoded, verify=False)

最新更新