1. 程式人生 > >Django通過中間件實現登錄驗證demo

Django通過中間件實現登錄驗證demo

ren pan tex title path_info csrf use doc lis

前提:中間件版的登錄驗證需要依靠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 ]
urls.py 技術分享圖片
 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")
views.py 技術分享圖片
 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>
login.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))
mymiddlewares.py 技術分享圖片
 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 ]
settings註冊中間件

AuthMD中間件註冊後,所有的請求都要走AuthMD的process_request方法。

如果URL在黑名單中,則返回This is an illegal URL的字符串;

訪問的URL在白名單內或者session中有user用戶名,則不做阻攔走正常流程;

正常的URL但是需要登錄後訪問,讓瀏覽器跳轉到登錄頁面。

註:AuthMD中間件中需要session,所以AuthMD註冊的位置要在session中間的下方。

Django通過中間件實現登錄驗證demo