【问题标题】:How authenticate with username, password and token in Django?如何在 Django 中使用用户名、密码和令牌进行身份验证?
【发布时间】:2020-06-03 10:28:28
【问题描述】:

我正在尝试使用用户名、密码和令牌对 Django 中的用户进行身份验证。所有这些都存储在数据库中。

#accounts/views.py
from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate, logout
from account.forms import RegistrationForm, AccountAuthenticationForm

def login_view(request):      
    if request.POST:
        form = AccountAuthenticationForm(request.POST)
        if form.is_valid():
            username = request.POST['username']
            password = request.POST['password']
            token = request.POST['token']
            user = authenticate(username = username, password = password, token = token)

            if user:
                login(request, user)
                return redirect("home")
    else:
        form = AccountAuthenticationForm()

    context['login_form'] = form
    return render(request, 'account/login.html', context)
#account/models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager

class MyAccountManager(BaseUserManager):
    def create_user(self, username, token, password=None):
        if not username:
            raise ValueError('Users must have an username')
        if not token:
            raise ValueError('Users must have a token')

        user = self.model(
            username = username,
            token = token,
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username, token, password=None):
        user = self.create_user(
            username = username,
            password = password,
            token = token,
        )

        user.is_admin = True
        user.is_staff = True
        user.is_superuser = True
        user.save(using=self._db)
        return user

可以使用正确的用户名/密码组合登录,但使用错误的令牌。

我做错了什么?

【问题讨论】:

    标签: django django-models django-authentication


    【解决方案1】:

    authenticate 函数根据用户名和密码执行查询并忽略令牌。这就是问题所在。

    所以解决办法是

    from django.contrib.auth import get_user_model
    ......
    if form.is_valid():
         username = request.POST['username']
         password = request.POST['password']
         token = request.POST['token']
         User = get_user_model()
         is_exists = User.objects.filter(username=username, token=token).exists()
         if is_exists:
           user = authenticate(username = username, password = password)
           ......
         else:
             # Perform validation error invalid token or username. 
    

    【讨论】:

      猜你喜欢
      • 2013-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-25
      • 2014-02-23
      • 2017-06-05
      • 2017-02-04
      • 2019-12-06
      相关资源
      最近更新 更多