【问题标题】:I have a problem with the django authenticate function我对 django 身份验证功能有疑问
【发布时间】:2020-09-19 20:41:08
【问题描述】:

当我输入与数据库中相同的用户名和密码时,它会显示“无效凭据”而不是“成功”。

def 登录(请求): 如果 request.method == 'POST':

    username           = request.POST.get('user')
    password1          = request.POST.get('password1')
    a                  = authenticate( username=username, password=password1)
    if a is not None:
        return HttpResponse("Success")
    else:
        return HttpResponse("Invalid Credentials")
return render(request, 'login.html')

【问题讨论】:

  • 您是如何创建用户的?密码是否经过哈希处理?
  • 实际上,我是直接在数据库中插入了用户名和密码。另外,我已经对密码进行了哈希处理。但是我正在尝试处理直接插入的值
  • 那么这行不通。 Django 在您创建用户时对密码进行哈希处理,如果哈希匹配,还会检查。在数据库中存储原始密码是一种严重的安全威胁。

标签: django authentication


【解决方案1】:

问题不在于身份验证本身,而在于创建用户。您不能在数据库中创建具有原始密码的用户。姜戈stores hashed passwords in the database。默认情况下使用 PBKDF2 散列器,尽管您可以对其进行配置。这意味着密码看起来像:

<i>algorithm</i>$<i>iterations</i>$<i>salt</i>$<i>hash</i>

身份验证模块将对您提供的密码进行哈希处理,并检查是否匹配。

您可以使用createsuperuser management command [Django-doc] 来创建超级用户:

django-admin <b>createsuperuser</b>

或者您可以使用changepassword management command [Django-doc] 更改用户的密码:

django-admin <b>changepassword</b> <i>username</i>

对于普通用户,您可以通过管理页面,或者在 shell 中使用.create_user(…) method [Django-doc]

$ python manage.py shell
Python 3.6.8 (default, Jan 14 2019, 11:02:34) 
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.contrib.auth import get_user_model
>>> get_user_model().objects.create_user(username='username', password='thepassword')
<User: username>

【讨论】:

    猜你喜欢
    • 2020-02-09
    • 1970-01-01
    • 1970-01-01
    • 2013-01-06
    • 2019-06-19
    • 2011-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多