django - django:无法使用 django 远程身份验证登录
问题描述
我正在开发一个新的 django 项目,我创建了一个简单的登录页面,我只想登录并转到主页。
当我尝试登录时,我得到并且登录没有成功。
项目名称:mysite 应用名称:dsmdata
下面是编码
- 项目(mysite) Settings.py 文件如下
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 2.1.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.environ['REMOTE_USER'] = "dsmuser1"
#LOGIN_URL = '/dsm/login'
# Redirect to home URL after login (Default redirects to /accounts/profile/)
#LOGIN_REDIRECT_URL = '/dsm/logged_in'
LOGIN_REDIRECT_URL = '/'
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'y%cwxi-m5s-0zct+k%$u1$z!#o#u52zu_!z*#8(8saqdx+6t$l'
# 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',
]
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.auth.middleware.RemoteUserMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates',],
'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 = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.RemoteUserBackend',
'dsmdata.pmauth.pmauth',
]
# Password validation
# https://docs.djangoproject.com/en/2.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/2.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/2.1/howto/static-files/
STATIC_URL = '/static/'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': 'C:/karthik/Projects/Postgres-DB-All/Statistics/debug.log',
},
},
'loggers': {
'django': {
'handlers': ['file'],
'level': 'DEBUG',
'propagate': True,
},
},
}
- 登录页面html:
{% extends 'base.html' %}
{% block content %}
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
{% if next %}
{% if user.is_authenticated %}
<p>Your account doesn't have access to this page. To proceed,
please login with an account that has access.</p>
{% else %}
<p>Please login to see this page.</p>
{% endif %}
{% endif %}
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="login-panel panel panel-default">
<div class="panel-heading">
<!-- <h3 class="panel-title">Please Sign In</h3> -->
</div>
<div class="panel-body">
<form method="post" action="{% url 'login' %}">
{% csrf_token %}
<p class="bs-component">
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td>{{ form.password }}</td>
</tr>
</table>
</p>
<p class="bs-component">
<center>
<input class="btn btn-success btn-sm" type="submit" value="login" />
</center>
</p>
<input type="hidden" name="next" value="{{ next }}" />
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% block javascript %}
<script>
{% if not user.is_authenticated %}
$("ul.nav.navbar-nav.navbar-right").css("display","none");
{% endif %}
</script>
{% endblock %}
- forms.py(来自我的应用程序,appname -dsmdata)
#log/forms.py
from django.contrib.auth.forms import AuthenticationForm
from django import forms
# If you don't do this you cannot use Bootstrap CSS
class LoginForm(AuthenticationForm):
username = forms.CharField(label="Username", max_length=30,
widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'username'}))
password = forms.CharField(label="Password", max_length=30,
widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'password'}))
- 我的自定义身份验证类派生自 RemoterUserBackend 类
from django.contrib.auth.models import User
from django.contrib.auth.backends import RemoteUserBackend
import logging
logger = logging.getLogger(__name__)
class pmauth(RemoteUserBackend):
def authenticate(self,request,username=None):
logger.debug("Inside authenticate")
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
# Create a new user. There's no need to set a password
# because only the password from settings.py is checked.
user = User(username=username)
user.is_staff = True
user.is_superuser = True
user.is_authenticated = True
# user.is_anonymous = abc.test
user.save()
return user
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
def configure_user(self,user):
"""Set user groups and privs.
This method is called the first time a non-django user logs in.
A user is created in the django database, this method
adds the new user to the appropriate groups, and
sets privs. """
#Add all remote users to a group
#user.groups.add(s.ALL_USERS_GROUP)
#all remote users are staff - so they can access the admin interface
user.is_staff=True
user.is_superuser=True
user.is_authenticated = True
user.is_anonymous = abc.test
logger.debug("Inside configure_user")
logger.debug(user.username)
#To determine if the user is to have further priviledges
#we consult LDAP
#connect to ldap server
# l = ldap.initialize(s.LDAP_SERVER)
#get list of superusers
# superusers=l.search_s(s.LDAP_SEARCH_TREE,\
# ldap.SCOPE_SUBTREE,\
# s.LDAP_FILTER)\
# [0][1][s.LDAP_FIELD]
#close LDAP Connection
# l.unbind()
#Check if this user should be a superuser.
# if user.username in superusers:
# user.is_superuser=True
#dsm.authenticate = true
user.save()
print("successfully saved the user")
return user
- 项目(我的网站) urls.py
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include,path
from django.urls import re_path
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from dsmdata.forms import LoginForm
from dsmdata.pmauth import pmauth
urlpatterns = [
#path('polls/', include('polls.urls')),
path('polls/', include('django.contrib.auth.urls')),
path('admin/', admin.site.urls),
re_path(r'', include('dsmdata.urls')),
url(r'^login/$', auth_views.LoginView.as_view() , {'template_name': 'login.html', 'authentication_form': LoginForm}, name="login" ),
#url(r'^login/$', pmauth , {'template_name': 'login.html', 'authentication_form': LoginForm}, name="login" ),
url(r'^logout/$', auth_views.LogoutView.as_view(), {'next_page': '/login'}),
#re_path(r'^dsm/',include('django.contrib.auth.urls')),
#re_path(r'^dsm/login', include('dsm.urls')),
]
- dsmdata 应用程序views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from pip._vendor.requests.api import request
# Create your views here.
# this login required decorator is to not allow to any
# view without authenticating
@login_required(login_url="login/")
def home(request):
return render(request,"home.html", testdict)
# Create your views here.
解决方案
推荐阅读
- python - 使用 Python 过滤 Excel 电子表格以获取单元格值
- dart - 如何获取下载文件夹的(绝对)路径?
- kotlin - 正确阅读和理解文档
- redis - 在 Redis / NoSQL 或关系数据库中存储大量数据?
- c# - 你将如何在 Unity 2D C# 中实现一个简单的聚合方法
- c - OpenSSL GFp 功能在替代 GF2m 功能方面是否会缓慢下降?
- javascript - CSS Grid:使网格列适合最宽的列
- sql - LEAD 功能 - 甲骨文
- python - TfDif 和自定义功能之间的 FeatureUnion 上的 KeyError
- image-processing - pickle.load() 和 pickle.dump() 不一致