Django通过中间件实现登录验证demo
Posted changwentao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django通过中间件实现登录验证demo相关的知识,希望对你有一定的参考价值。
前提:中间件版的登录验证需要依靠session,所以数据库中要有django_session表。
1 from django.conf.urls import url 2 from django.contrib import admin 3 from app01 import views 4 5 urlpatterns = [ 6 url(r‘^admin/‘, admin.site.urls), 7 url(r‘^login/$‘, views.login, name=‘login‘), 8 url(r‘^index/$‘, views.index, name=‘index‘), 9 url(r‘^home/$‘, views.home, name=‘home‘), 10 ]
1 from django.shortcuts import render, HttpResponse, redirect 2 3 4 def index(request): 5 return HttpResponse(‘this is index‘) 6 7 8 def home(request): 9 return HttpResponse(‘this is home‘) 10 11 12 def login(request): 13 if request.method == "POST": 14 user = request.POST.get("user") 15 pwd = request.POST.get("pwd") 16 17 if user == "jason" and pwd == "jason666": 18 # 设置session 19 request.session["user"] = user 20 # 获取跳到登陆页面之前的URL 21 next_url = request.GET.get("next") 22 # 如果有,就跳转回登陆之前的URL 23 if next_url: 24 return redirect(next_url) 25 # 否则默认跳转到index页面 26 else: 27 return redirect("/index/") 28 return render(request, "login.html")
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>登录页面</title> 6 </head> 7 <body> 8 <form action="{% url ‘login‘ %}" method="post"> 9 {% csrf_token %} 10 <p> 11 <label for="user">用户名:</label> 12 <input type="text" name="user" id="user"> 13 </p> 14 <p> 15 <label for="pwd">密 码:</label> 16 <input type="text" name="pwd" id="pwd"> 17 </p> 18 <input type="submit" value="登录"> 19 </form> 20 </body> 21 </html>
1 from django.utils.deprecation import MiddlewareMixin 2 3 4 class AuthMD(MiddlewareMixin): 5 white_list = [‘/login/‘, ] # 白名单 6 black_list = [‘/black/‘, ] # 黑名单 7 8 def process_request(self, request): 9 from django.shortcuts import redirect, HttpResponse 10 11 next_url = request.path_info 12 print(request.path_info, request.get_full_path()) 13 # 黑名单的网址限制访问 14 if next_url in self.black_list: 15 return HttpResponse(‘This is an illegal URL‘) 16 # 白名单的网址或者登陆用户不做限制 17 elif next_url in self.white_list or request.session.get("user"): 18 return 19 else: 20 return redirect("/login/?next={}".format(next_url))
1 MIDDLEWARE = [ 2 ‘django.middleware.security.SecurityMiddleware‘, 3 ‘django.contrib.sessions.middleware.SessionMiddleware‘, 4 ‘django.middleware.common.CommonMiddleware‘, 5 ‘django.middleware.csrf.CsrfViewMiddleware‘, 6 ‘django.contrib.auth.middleware.AuthenticationMiddleware‘, 7 ‘django.contrib.messages.middleware.MessageMiddleware‘, 8 ‘django.middleware.clickjacking.XFrameOptionsMiddleware‘, 9 ‘app01.mymiddlewares.AuthMD‘ 10 ]
AuthMD中间件注册后,所有的请求都要走AuthMD的process_request方法。
如果URL在黑名单中,则返回This is an illegal URL的字符串;
访问的URL在白名单内或者session中有user用户名,则不做阻拦走正常流程;
正常的URL但是需要登录后访问,让浏览器跳转到登录页面。
注:AuthMD中间件中需要session,所以AuthMD注册的位置要在session中间的下方。
以上是关于Django通过中间件实现登录验证demo的主要内容,如果未能解决你的问题,请参考以下文章
Express实战 - 应用案例- realworld-API - 路由设计 - mongoose - 数据验证 - 密码加密 - 登录接口 - 身份认证 - token - 增删改查API(代码片段