【Django学习笔记5】opneLDAP服务来创建账户登录系统

2021-01-12  本文已影响0人  Geekero

学习自极客时间吕老师Django课程

创建账户登录系统

与企业的域账号进行管理(目录服务)
Directory Service
OpenLDAP服务(Lightweight Directory Access Protocol) / ActiveDirectory

DN:目录服务中的一个唯一的对象
000000000

用docker 安装 OpenLDAP

$docker run -p 389:389 -p 636:636 --name my-openldap-container --env LDAP_ORGANISATION="ihopeit" --env LDAP_DOMAIN="ihopeit.com" --env LDAP_ADMIN_PASSWORD="admin_passwd_4_ldap" --detach osixia/openldap:1.4.0
$docker run -p 443:443 -p 80:80 --env PHPLDAPADMIN_LDAP_HOSTS=ldap-host --name phpldapadmin-service --hostname phpldapadmin-service --link my-openldap-container:ldap-host --detach osixia/phpldapadmin:0.9.0

开放389和443端口到外网(不建议开放80端口)

$docker ps
CONTAINER ID   IMAGE                       COMMAND                 CREATED       STATUS       PORTS                                        NAMES
5d83aa239cf4   osixia/phpldapadmin:0.9.0   "/container/tool/run"   5 hours ago   Up 5 hours   0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp     phpldapadmin-service
a1b74166b2c7   osixia/openldap:1.4.0       "/container/tool/run"   7 hours ago   Up 7 hours   0.0.0.0:389->389/tcp, 0.0.0.0:636->636/tcp   my-openldap-container

安装App: django-python3-ldap

pip install django-python3-ldap

在全局setting中加入app:django-python3-ldap

(Django) 17:47 luohb@Studynode:~/Django/recruitment/recruitment 
$vi settings.py 

注册

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_python3_ldap',
    'jobs',
    'interview',
]

配置:最后一行加入

# The URL of LDAP server.
LDAP_AUTH_URL = "ldap://192.168.3.36:389" #服务器地址

登录管理系统:
访问界面:http://实际ip/phpldapadmin/

报错:

You don't have permission to access /ldapadmin on this server 

解决:
http://www.voidcn.com/article/p-tqbfvgon-brk.html
https://www.jb51.net/article/97434.htm

登录

创建用户

配置Django全局setting

(Django) 19:30 luohb@Studynode:~/Django/recruitment/recruitment 
$cat settings.py 
"""
Django settings for recruitment project.

Generated by 'django-admin startproject' using Django 3.1.4.

For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '_d2vg!z2=^msv$9eas-vhfk_qw5n4r%z59cz5#lx_2v15o4!_('

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_python3_ldap',
    'jobs',
    'interview',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'recruitment.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'recruitment.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


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


# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_URL = '/static/'

# The URL of LDAP server.
LDAP_AUTH_URL = "ldap://192.168.3.36:389" #服务器地址

#Initiate TLS on connection.
LDAP_AUTH_USE_TLS = False

#The LDAP search base for looking up users.
LDAP_AUTH_SEARCH_BASE = "dc=ihopeit,dc=com"

#The LDAP class that represents a user.
LDAP_AUTH_OBJECT_CLASS = "inetOrgPerson" #认证用户的类型,哪些资源用户可以登录; 这里用的是组织的人员(域服务人员的系统)

#User model fileds mapped to the LDAP
#attributes that represents them.
LDAP_AUTH_USER_FIELDS = {
    "username":"cn",
    "first_name":"givenName",
    "last_name":"sn",
    "email":"mail",
}

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

# Path to a callable taht takes a dict of {model_field_name: value},
LDAP_AUTH_CLEAN_USER_DATA = "django_python3_ldap.utils.clean_user_data"

# The LDAP username and passward of a user will be used for quering, and 
#the 'ldap_sync_user' command will perform an anonymous query.
LDAP_AUTH_CONNECTION_USERNAME = "admin"
LDAP_AUTH_CONNECTION_PASSWORD = "JonSn0wbcxnwei3529"

AUTHENTICATION_BACKENDS = {"django_python3_ldap.auth.LDAPBackend", "django.contrib.auth.backends.ModelBackend",} #2种方式登录认证服务

启动服务

(Django) 19:31 luohb@Studynode:~/Django/recruitment 
$python manage.py  runserver 0.0.0.0:8000
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
January 11, 2021 - 11:31:32
Django version 3.1.4, using settings 'recruitment.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.

第一次登录时会Django会同步这个域账号,但不是一个员工

上一篇下一篇

猜你喜欢

热点阅读