简体   繁体   English

如何使用LDAP在Django中检查密码?

[英]How to check a password in Django with LDAP?

I have a django page when users have to type again his password to confirm an action. 当用户必须再次输入密码以确认操作时,我有一个django页面。 The user is already on (logged), but to do this action he must "sign" confirming his password. 用户已经登录(登录),但是要执行此操作,他必须“签名”以确认密码。

Users are authenticating with LDAP (Active Directory). 用户正在使用LDAP(Active Directory)进行身份验证。 I tried to use something like that but it always return false, even when password is correct: 我尝试使用类似的方法,但是即使密码正确也总是返回false:

def check_password(request):
  """This method will compare logged user password with typed password"""
  password = request.POST.get('password', None)
  user = request.user.username

  result = request.user.check_password(password)

  if result:
      return JsonResponse({'status': 'true'})
  else:
      return JsonResponse({'status': 'false'})

Django Version: 2.0.2 Python: 3.6.x Django版本:2.0.2 Python:3.6.x

Someone can help me? 有人可以帮我吗? Thank you in advance. 先感谢您。


Follow my settings.py 按照我的settings.py

# Password validation
# https://docs.djangoproject.com/en/1.11/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',
    },
]

# Active Directory Authentication
# Source: https://github.com/etianen/django-python3-ldap
# The URL of the LDAP server.
LDAP_AUTH_URL = "ldap://some-address.local:389"
AUTHENTICATION_BACKENDS = (
    "django_python3_ldap.auth.LDAPBackend",
)
# Initiate TLS on connection.
LDAP_AUTH_USE_TLS = False

# The LDAP search base for looking up users.
# LDAP_AUTH_SEARCH_BASE = "ou=****,ou=***,dc=***,dc=local"
LDAP_AUTH_SEARCH_BASE = "dc=***,dc=local"

# ,dc=example

# The LDAP class that represents a user.
LDAP_AUTH_OBJECT_CLASS = "User"

# User model fields mapped to the LDAP
# attributes that represent them.
LDAP_AUTH_USER_FIELDS = {
    "username": "sAMAccountName",
    "first_name": "givenName",
    "last_name": "sn",
    "email": "mail",
    "badge": "description",
}

# A tuple of django model fields used to uniquely identify a user.
LDAP_AUTH_USER_LOOKUP_FIELDS = ("username",)

# Path to a callable that takes a dict of {model_field_name: value},
# returning a dict of clean model data.
# Use this to customize how data loaded from LDAP is saved to the User model.
LDAP_AUTH_CLEAN_USER_DATA = "django_python3_ldap.utils.clean_user_data"

# Path to a callable that takes a user model and a dict of {ldap_field_name: [value]},
# and saves any additional user relationships based on the LDAP data.
# Use this to customize how data loaded from LDAP is saved to User model relations.
# For customizing non-related User model fields, use LDAP_AUTH_CLEAN_USER_DATA.
LDAP_AUTH_SYNC_USER_RELATIONS = "django_python3_ldap.utils.sync_user_relations"

# Path to a callable that takes a dict of {ldap_field_name: value},
# returning a list of [ldap_search_filter]. The search filters will then be AND'd
# together when creating the final search filter.
LDAP_AUTH_FORMAT_SEARCH_FILTERS = "django_python3_ldap.utils.format_search_filters"

# Path to a callable that takes a dict of {model_field_name: value}, and returns
# a string of the username to bind to the LDAP server.
# Use this to support different types of LDAP server.
LDAP_AUTH_FORMAT_USERNAME = "django_python3_ldap.utils.format_username_active_directory"

# Sets the login domain for Active Directory users.
LDAP_AUTH_ACTIVE_DIRECTORY_DOMAIN = "my_domain"

# The LDAP username and password of a user for querying the LDAP database for user
# details. If None, then the authenticated user will be used for querying, and
# the `ldap_sync_users` command will perform an anonymous query.
LDAP_AUTH_CONNECTION_USERNAME = "**********"
LDAP_AUTH_CONNECTION_PASSWORD = "*********"

# Set connection/receive timeouts (in seconds) on the underlying `ldap3` library.
LDAP_AUTH_CONNECT_TIMEOUT = 1000
LDAP_AUTH_RECEIVE_TIMEOUT = 1000

# Log Failed logins from Active Directory
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
        },
    },
    "loggers": {
        "django_python3_ldap": {
            "handlers": ["console"],
            "level": "INFO",
        },
    },
}

LDAP user are not a Django user. LDAP用户不是Django用户。 So you need to check the password with your LDAP system and not Django one. 因此,您需要使用LDAP系统而不是Django来检查密码。

One good practice IMO is to create an django user for each LDAP user you have and set the password at first login, so when your LDAP is offline at least existing django user can login (and you can use check_password ) IMO的一个好作法是为您拥有的每个LDAP用户创建一个django用户,并在首次登录时设置密码,因此,当LDAP脱机时,至少现有的django用户可以登录(并且您可以使用check_password

I solved this problem today by use a diferent method - authenticate. 我今天通过使用另一种方法-身份验证解决了这个问题。 I did this way and it works: 我这样做,它的工作原理是:

def ajax_check_password(request):
   """This method will compare logged user password with typed password"""
   password = str(request.POST.get('password', None))
   result = authenticate(username=request.user.username, password=password)

   if result:
      return JsonResponse({'status': 'true'})
   else:
      return JsonResponse({'status': 'false'})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM