一,校检密码:
1, 校检密码 使用的是 django 自带的 权限组件 django.contrib.auth 自定义校检类
2, authenticate(user=user, password=password) 会调用自定义的校检类(配置文件进行检查!)
3, 需要setting 指定 AUTHENTICATION_BACKENDS (自定义的校检类)
自定义的校检类:
import logging
from django.conf import settings
from rest_framework.authentication import (
BaseAuthentication, get_authorization_header,
)
from rest_framework.exceptions import AuthenticationFailed, PermissionDenied
from six import raise_from
from .managers.pam import auth
from .models import User
logger = logging.getLogger(__name__)
class AuthBackend(object):
# 需要重写 authentication 方法
def authenticate(
self, user=None,
password=None,
**kwargs
):
username = user.username
from pamela import PAMError
try:
# 使用自定义的 认证
auth(username, password)
except PAMError:
logger.warn(
'Invalid user[ %s ]', username,
exc_info=True
)
return None
else:
return user
View Code
setting 文件指定检验类:
AUTHENTICATION_BACKENDS = (
# 指定自定义的 校检类
# 此类只是检验密码的作用!
'antilles.user.plugins.AuthBackend',
)
# pamela 需要用到
LICO_PAM_SERVICE = 'lico
自定义认证:
import logging
from django.conf import settings
from six import raise_from
def auth(username, password):
# pamela 是一个 Python 的可插入认证模块(PAM)库的接口。
from pamela import authenticate, open_session, PAMError
try:
authenticate(username, password, service=settings.LICO_PAM_SERVICE)
except PAMError:
raise
try:
open_session(username, service=settings.LICO_PAM_SERVICE)
except PAMError:
logger.exception('Error call "open_session"')
def change_password(username, password):
from pamela import change_password, PAMError
try:
change_password(username, password, service=settings.LICO_PAM_SERVICE)
except PAMError as e:
raise_from(
ModifyPasswordException(e),
e
)
密码认证是采用的 linux PAM 认证
1, pamela 呼叫 PAM 模块进行验证;
2, PAM 模块会到 /etc/pam.d/ 找寻与程序 (passwd) 同名的配置文件;
3, 依据 /etc/pam.d/passwd 内的配置,引用相关的 PAM 模块逐步进行验证分析;
4, 将验证结果 (成功、失败以及其他信息) 回传给 pamela 这支程序;
5, 模块实际在 /lib/security/