我正在开发一个 django 应用程序,我必须在其中验证来自活动目录的用户。 我可以在 CustomAuthenticationBackend 中使用以下代码来完成:
def authenticate(self, request, **kwargs):
username = kwargs['username']
password = kwargs['password']
# type = kwargs['userType']
adConnect,message = self.is_valid_ad(username, password)
if adConnect:
request.session['pss'] = password
try:
userExist = User.objects.get(username__iexact=username)
if userExist.check_password(password) is True:
return userExist
else:
pass
except User.DoesNotExist:
# raise ValidationError(username+" is not allowed to access this application.")
return self.createNewUserFromAD(adConnect, username, password)
else:
pass
并在 settings.py
AUTHENTICATION_BACKENDS = (
'dcw_app.CustomBackendAuth.CustomBackendAuth',
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
)
在网址中:
path('login/', auth_views.LoginView.as_view(template_name='dcw_app/login.html'), name='login'),
当我需要在登录表单中添加额外字段时出现问题。身份验证不会发生,提交表单只是重新加载。自定义表单在forms.py中是这样的:
class UserLoginForm(AuthenticationForm):
errors = {
'required': 'Admin Must enter at least one role.',
}
def __init__(self, *args, **kwargs):
super(UserLoginForm, self).__init__(*args, **kwargs)
userType = forms.ChoiceField(error_messages=errors,required=True,
label=pgettext("field label","Role"),widget=forms.Select(attrs={'class': 'form-control', 'placeholder': '', 'id': 'userType'}), choices=UserModal.USER_ROLES,)
在 urls.py 中
path('login/', auth_views.LoginView.as_view(template_name='dcw_app/login.html',authentication_form=UserLoginForm), name='login'),
答案 0 :(得分:0)
此角色是否作为服务器提供的内容差异的条件? 如果是这样,你可以尝试这样的事情:
def authenticate(self, request, **kwargs):
username = kwargs['username']
password = kwargs['password']
# type = kwargs['userType']
adConnect,message = self.is_valid_ad(username, password)
if adConnect:
request.session['pss'] = password
try:
userExist = User.objects.get(username__iexact=username)
if userExist.check_password(password) is True:
if userType is "foo":
#do something 1
else if userType is "bar":
#do something 2
else:
pass
except User.DoesNotExist:
# raise ValidationError(username+" is not allowed to access this application.")
return self.createNewUserFromAD(adConnect, username, password)
else:
pass
另一种方法是在数据库本身中创建帐户类型并使用该类型使用相同条件进行服务