Django要求我发送一个哈希密码以获取我的JWT令牌。通过邮递员发送以下请求时,出现“ CustomUser匹配查询不存在”错误。
{
"user": {
"email": "myuser",
"password": "mypassword"
}
}
但是,我可以使用带哈希密码的代码运行代码(从管理员那里查找之后),它返回正确的值。在发送密码之前,如何发送未加密的密码或对密码进行哈希处理?
我使用的是自定义用户模型,该模型将电子邮件替换为用户名。我尝试使用request.META.get("username")
和request.META.get("password")
将代码指向标题,但收到“必填字段”错误。我还试图找出如何在将应用程序密码发送给我的API之前对其进行哈希处理,但是我找不到能起作用的方法。
我在下面有处理请求的看法。
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
def login(request):
username = request.data.get('username')
password = request.data.get('password')
if username is None or password is None:
return Response({'error': 'Please provide your username and password'}, status=HTTP_400_BAD_REQUEST)
user = authenticate(email=username, password=password)
if not user:
return Response({'error': 'Invalid Credentials'},status=HTTP_404_NOT_FOUND)
token, _ = Token.objects.get_or_create(user=user)
return Response({'token': token.key}, status=HTTP_200_OK)
我希望获得一个JWT令牌,但是却收到了“ CustomUser匹配查询不存在”或“必填字段”
编辑-----添加我的自定义模型---
import jwt
from datetime import datetime, timedelta
from django.conf import settings
from django.contrib.auth.models import (
AbstractBaseUser, BaseUserManager, PermissionsMixin
)
from django.db import models
class UserManager(BaseUserManager):
def create_user(self, username, email, password=None):
if username is None:
raise TypeError('Users must have a username')
if email is None:
raise TypeError('Users must have an email address')
user = self.model(username=username, email=self.normalize_email(email))
user.set_password(password)
user.save()
return user
def create_superuser(self, username, email, password):
if password is None:
raise TypeError('Superusers must have a password')
user = self.create_user(username, email, password)
user.is_superuser = True
user.is_staff = True
user.save()
return user
class CustomUser(AbstractBaseUser, PermissionsMixin):
username = models.CharField(db_index=True, max_length=255, unique = True)
email = models.EmailField(db_index=True, unique=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
objects = UserManager()
def __str__(self):
return self.email
@property
def token(self):
return self._generate_jwt_token()
def get_full_name(self):
return self.username
def get_short_name(self):
return self.username
def _generate_jwt_token(self):
dt = datetime.now()
expr = dt + timedelta(days=60)
dtt = int(expr.timestamp())
token = jwt.encode({
'id':self.pk,
'exp': dtt,
}, settings.SECRET_KEY, algorithm='HS256')
return token.decode('utf-8')
答案 0 :(得分:0)
我知道了我的问题。在实施JWT时,我在线保留了Django的默认版本身份验证。我决定删除JWT,而不是重新设计所有内容。现在,它可以完美运行。