Django drf simple-jwt authentication"detail": "没有找到具有给定凭据的活动帐户"

A.J*_*JRJ 10 django django-rest-framework django-rest-framework-simplejwt

我正在使用带有自定义用户的 django-rest_framework_simple-jwt 实现用户身份验证,我的 models.py:

class UserManager(BaseUserManager):
    def create_user(self, email, username, password, alias=None):
        user = self.model(
        email = self.normalize_email(email),
                username = username,)
        user.set_password(password)
        user.save()
        return user
   def create_superuser(self, email, username, password):
       self.create_user(email, username, password)
       user.is_staff()
       user.is_superuser = True
       user.save()
       return user

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(null=False, unique=True)
    username = models.CharField(max_length=25, unique=True)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)

    objects = UserManager()
    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = ["username",]
Run Code Online (Sandbox Code Playgroud)

所以我正在实现restframework simple-jwt身份验证,我的设置.py如下:

REST_FRAMEWORK={
  'DEFAULT_AUTHENTICATION_CLASSES': [
      'rest_framework_simplejwt.authentication.JWTAuthentication',
   ]}
Run Code Online (Sandbox Code Playgroud)

我的 urls.py:

urlpatterns = [
       url(r'^api/token/$', TokenObtainPairView.as_view(),  name='token_obtain_pair'),
       url(r'^api/token/refresh/$', TokenRefreshView.as_view(), name='token_refresh'),]
Run Code Online (Sandbox Code Playgroud)

在登录过程中,它返回错误,指出"detail": "No active account found with the given credentials"我的所有用户都处于活动状态。我不知道解决这个问题,我需要帮助。提前致谢。

Kea*_*els 19

确保您的密码在存储在您的数据库中之前已经过哈希处理。我遇到了同样的问题,发现我的密码是以纯文本形式存储的。将以下内容添加到我的 UserSerializer 解决了这个问题

from django.contrib.auth.hashers import make_password

def validate_password(self, value: str) -> str:
    """
    Hash value passed by user.

    :param value: password of a user
    :return: a hashed version of the password
    """
    return make_password(value)
Run Code Online (Sandbox Code Playgroud)

  • 谢谢我对我有用。就我而言,密码经过两次哈希处理,因为我在验证中进行了哈希处理,就像您建议的那样,然后我使用了 user.set_password ,它也对其进行了哈希处理。 (2认同)

Leo*_*oog 1

您是否记得在设置中进行设置:

AUTH_USER_MODEL = 'your_app_name.User'
Run Code Online (Sandbox Code Playgroud)