django中使用cookie和session驗證用戶是否已登錄


為什么需要使用cookie和session?

HTTP協議本身是”無狀態”的,在一次請求和下一次請求之間沒有任何狀態保持,服務器無法識別來自同一用戶的連續請求。有了cookie和session,服務器就可以利用它們記錄客戶端的訪問狀態了,這樣用戶就不用在每次訪問不同頁面都需要登錄了。

 

什么是cookie,cookie的應用場景及缺點

cookie是一種數據存儲技術, 它是將一段文本保存在客戶端(瀏覽器或本地電腦)的一種技術,並且可以長時間的保存。當用戶首次通過客戶端訪問服務器時,web服務器會發送給客戶端的一小段信息。客戶端瀏覽器會將這段信息以cookie形式保存在本地某個目錄下的文件內。當客戶端下次再發送請求時會自動將cookie也發送到服務器端,這樣服務器端通過查驗cookie內容就知道該客戶端早訪問過了。

 

cookie的常見應用場景包括:

  • 判斷用戶是否已經登錄

  • 記錄用戶登錄信息(比如用戶名,上次登錄時間)

  • 記錄用戶搜索關鍵詞

 

cookie的缺點在於其並不可靠不安全,主要原因如下:

  • 瀏覽器不一定會保存服務器發來的cookie,用戶可以通過設置選擇是否保存cookie。

  • cookie是有生命周期的(通過Expire設置),如果超過周期,cookie就會被清除。

  • HTTP數據通過明文發送,容易受到攻擊,因此不能在cookie中存放敏感信息(比如信用卡號,密碼等)。

  • cookie以文件形式存儲在客戶端,用戶可以隨意修改的。

 

利用cookie驗證用戶是否已經登錄:

 1 def login(request):
 2     if request.method == 'POST':
 3         form = LoginForm(request.POST)
 4         
 5         if form.is_valid():
 6             username = form.cleaned_data['username']
 7             password = form.cleaned_data['password']
 8             
 9             user = User.objects.filter(username__exact=username,passowrd__exact==password)
10             
11             if user:
12                 response = HttpResponseRedirect('/index/')
13                     #將username寫入瀏覽器cookie,失效時間為360s
14                     response.set_cookie('username',username,3600)
15                 return response
16             else:
17                 return HttpResponstRedirect('/login/')
18         
19     else:
20         form = LoginForm()
21     return render(request,'users/login.html',{'form':form})
22     
23 #通過cookie判斷用戶是否已登錄
24 def index(request):
25     #提取瀏覽器中的cookie,如果不為空,表示已經登錄
26     username = request.COOKIES.get('username','')
27     if not uername:
28         return HttpResponseRedirect('/login/')
29     return render(request,'index.html',{'username':username})
View Code

 

什么是session及session的工作原理

session又名會話,其功能與應用場景與cookie類似,用來存儲少量的數據或信息。但由於數據存儲在服務器上,而不是客戶端上,所以比cookie更安全。

 

Session工作的流程如下:

  • 客戶端向服務器發送請求時,看本地是否有cookie文件。如果有,就在HTTP的請求頭(Request Headers)中,包含一行cookie信息。

  • 服務器接收到請求后,根據cookie信息,得到sessionId,根據sessionId找到對應的session,用這個session就能判斷出用戶是否登錄等等。

 

使用Session的好處在於,即使用戶關閉了瀏覽器,session仍將保持到會話過期。

 

django中用session驗證用戶登錄狀態

 1 # 如果登錄成功,設置session
 2 def login(request):
 3     if request.method == 'POST':
 4         form = LoginForm(request.POST)
 5 
 6         if form.is_valid():
 7             username = form.cleaned_data['username']
 8             password = form.cleaned_data['password']
 9 
10             user = User.objects.filter(username__exact=username, password__exact=password)
11 
12             if user:
13                 # 將username寫入session,存入服務器
14                 request.session['username'] = username
15                 return HttpResponseRedirect('/index/')
16 
17             else:
18                 return HttpResponseRedirect('/login/')
19 
20     else:
21         form = LoginForm()
22 
23     return render(request, 'users/login.html', {'form': form})
24 
25 
26 # 通過session判斷用戶是否已登錄
27 def index(request):
28 
29     # 獲取session中username
30     username = request.session.get('username', '')
31     if not username:
32         return HttpResponseRedirect('/login/')
33     return render(request, 'index.html', {'username': username})
View Code

 下面是通過session控制不讓用戶連續評論兩次的例子。實際應用中我們還可以通過session來控制用戶登錄時間,單位時間內連續輸錯密碼次數等等。

 1 from django.http import HttpResponse
 2 
 3 
 4 def post_comment(request, new_comment):
 5     if request.session.get('has_commented', False):
 6         return HttpResponse("You've already commented.")
 7     c = comments.Comment(comment=new_comment)
 8     c.save()
 9     request.session['has_commented'] = True
10     return HttpResponse('Thanks for your comment!')
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM