Django Session和Cookie分別實(shí)現(xiàn)記住用戶登錄狀態(tài)操作
簡(jiǎn)介
由于http協(xié)議的請(qǐng)求是無(wú)狀態(tài)的。故為了讓用戶在瀏覽器中再次訪問(wèn)該服務(wù)端時(shí),他的登錄狀態(tài)能夠保留(也可翻譯為該用戶訪問(wèn)這個(gè)服務(wù)端其他網(wǎng)頁(yè)時(shí)不需再重復(fù)進(jìn)行用戶認(rèn)證)。我們可以采用Cookie或Session這兩種方式來(lái)讓瀏覽器記住用戶。
Cookie與Session說(shuō)明與實(shí)現(xiàn)
Cookie
說(shuō)明
Cookie是一段小信息(數(shù)據(jù)格式一般是類似key-value的鍵值對(duì)),由服務(wù)器生成,并發(fā)送給瀏覽器讓瀏覽器保存(保存時(shí)間由服務(wù)端定奪)。當(dāng)瀏覽器下次訪問(wèn)該服務(wù)端時(shí),會(huì)將它保存的Cookie再發(fā)給服務(wù)器,從而讓服務(wù)器根據(jù)Cookie知道是哪個(gè)瀏覽器或用戶在訪問(wèn)它。(由于瀏覽器遵從的協(xié)議,它不會(huì)把該服務(wù)器的Cookie發(fā)送給另一個(gè)不同host的服務(wù)器)。
Django中實(shí)現(xiàn)Cookie
from django.shortcuts import render, redirect# 設(shè)置cookie'''key: cookie的名字value: cookie對(duì)應(yīng)的值max_age: cookie過(guò)期的時(shí)間'''response.set_cookie(key, value, max_age)# 為了安全,有時(shí)候我們會(huì)調(diào)用下面的函數(shù)來(lái)給cookie加鹽response.set_signed_cookie(key,value,salt=’加密鹽’,...)# 獲取cookie request.COOKIES.get(key)request.get_signed_cookie(key, salt='加密鹽', default=None)# 刪除cookiereponse.delete_cookie(key)
下面就是具體的代碼實(shí)現(xiàn)了
views.py
# 編寫裝飾器檢查用戶是否登錄def check_login(func): def inner(request, *args, **kwargs): next_url = request.get_full_path() # 假設(shè)設(shè)置的cookie的key為login,value為yes if request.get_signed_cookie('login', salt='SSS', default=None) == ’yes’: # 已經(jīng)登錄的用戶,則放行 return func(request, *args, **kwargs) else: # 沒(méi)有登錄的用戶,跳轉(zhuǎn)到登錄頁(yè)面 return redirect(f'/login?next={next_url}') return inner# 編寫用戶登錄頁(yè)面的控制函數(shù)@csrf_exemptdef login(request): if request.method == 'POST': username = request.POST.get('username') passwd = request.POST.get('password') next_url = request.POST.get('next_url') # 對(duì)用戶進(jìn)行驗(yàn)證,假設(shè)用戶名為:aaa, 密碼為123 if username === ’aaa’ and passwd == ’123’: # 執(zhí)行其他邏輯操作,例如保存用戶信息到數(shù)據(jù)庫(kù)等 # print(f’next_url={next_url}’) # 登錄成功后跳轉(zhuǎn),否則直接回到主頁(yè)面 if next_url and next_url != '/logout/': response = redirect(next_url) else: response = redirect('/index/') # 若登錄成功,則設(shè)置cookie,加鹽值可自己定義取,這里定義12小時(shí)后cookie過(guò)期 response.set_signed_cookie('login', ’yes’, salt='SSS', max_age=60*60*12) return response else: # 登錄失敗,則返回失敗提示到登錄頁(yè)面 error_msg = ’登錄驗(yàn)證失敗,請(qǐng)重新嘗試’ return render(request, 'app/login.html', { ’login_error_msg’: error_msg, ’next_url’: next_url, }) # 用戶剛進(jìn)入登錄頁(yè)面時(shí),獲取到跳轉(zhuǎn)鏈接,并保存 next_url = request.GET.get('next', ’’) return render(request, 'app/login.html', { ’next_url’: next_url })# 登出頁(yè)面def logout(request): rep = redirect('/login/') # 刪除用戶瀏覽器上之前設(shè)置的cookie rep.delete_cookie(’login’) return rep# 給主頁(yè)添加登錄權(quán)限認(rèn)證@check_logindef index(request): return render(request, 'app/index.html')
由上面看出,其實(shí)就是在第一次用戶登錄成功時(shí),設(shè)置cookie,用戶訪問(wèn)其他頁(yè)面時(shí)進(jìn)行cookie驗(yàn)證,用戶登出時(shí)刪除cookie。另外附上前端的login.html部分代碼
<form action='{% url ’login’ %}' method='post'> <h1>請(qǐng)使xx賬戶登錄</h1> <div> <input type='text' name='username' placeholder='賬戶' required='' /> </div> <div> <input type='password' name='password' placeholder='密碼' required='' /> </div> <div style='display: none;'> <input type='text' name='next_url' value='{{ next_url }}' /> </div> {% if login_error_msg %} <div id='error-msg'> <span style='color: rgba(255,53,49,0.8); font-family: cursive;'>{{ login_error_msg }}</span> </div> {% endif %} <div> <button type='submit' style='float: initial; margin-left: 0px'>登錄</button> </div> </form>
Session
Session說(shuō)明
Session則是為了保證用戶信息的安全,將這些信息保存到服務(wù)端進(jìn)行驗(yàn)證的一種方式。但它卻依賴于cookie。具體的過(guò)程是:服務(wù)端給每個(gè)客戶端(即瀏覽器)設(shè)置一個(gè)cookie(從上面的cookie我們知道,cookie是一種”key, value“形式的數(shù)據(jù),這個(gè)cookie的value是服務(wù)端隨機(jī)生成的一段但唯一的值)。
當(dāng)客戶端下次訪問(wèn)該服務(wù)端時(shí),它將cookie傳遞給服務(wù)端,服務(wù)端得到cookie,根據(jù)該cookie的value去服務(wù)端的Session數(shù)據(jù)庫(kù)中找到該value對(duì)應(yīng)的用戶信息。(Django中在應(yīng)用的setting.py中配置Session數(shù)據(jù)庫(kù))。
根據(jù)以上描述,我們知道Session把用戶的敏感信息都保存到了服務(wù)端數(shù)據(jù)庫(kù)中,這樣具有較高的安全性。
Django中Session的實(shí)現(xiàn)
# 設(shè)置session數(shù)據(jù), key是字符串,value可以是任何值request.session[key] = value# 獲取 sessionrequest.session.get[key]# 刪除 session中的某個(gè)數(shù)據(jù)del request.session[key]# 清空session中的所有數(shù)據(jù)request.session.delete()
下面就是具體的代碼實(shí)現(xiàn)了:
首先就是設(shè)置保存session的數(shù)據(jù)庫(kù)了。這個(gè)在setting.py中配置:(注意我這里數(shù)據(jù)庫(kù)用的mongodb,并使用了django_mongoengine庫(kù);關(guān)于這個(gè)配置請(qǐng)根據(jù)自己使用的數(shù)據(jù)庫(kù)進(jìn)行選擇,具體配置可參考官方教程)
SESSION_ENGINE = ’django_mongoengine.sessions’
SESSION_SERIALIZER = ’django_mongoengine.sessions.BSONSerializer’
views.py
# 編寫裝飾器檢查用戶是否登錄def check_login(func): def inner(request, *args, **kwargs): next_url = request.get_full_path() # 獲取session判斷用戶是否已登錄 if request.session.get(’is_login’): # 已經(jīng)登錄的用戶... return func(request, *args, **kwargs) else: # 沒(méi)有登錄的用戶,跳轉(zhuǎn)剛到登錄頁(yè)面 return redirect(f'/login?next={next_url}') return inner@csrf_exemptdef login(request): if request.method == 'POST': username = request.POST.get('username') passwd = request.POST.get('password') next_url = request.POST.get('next_url') # 若是有記住密碼功能 # remember_sign = request.POST.get('check_remember') # print(remember_sign) # 對(duì)用戶進(jìn)行驗(yàn)證 if username == ’aaa’ and passwd == ’123’: # 進(jìn)行邏輯處理,比如保存用戶與密碼到數(shù)據(jù)庫(kù) # 若要使用記住密碼功能,可保存用戶名、密碼到session # request.session[’user_info’] = { # ’username’: username, # ’password’: passwd # } request.session[’is_login’] = True # 判斷是否勾選了記住密碼的復(fù)選框 # if remember_sign == ’on’: # request.session[’is_remember’] = True # else: # request.session[’is_remember’] = False # print(f’next_url={next_url}’) if next_url and next_url != '/logout/': response = redirect(next_url) else: response = redirect('/index/') return response else: error_msg = ’登錄驗(yàn)證失敗,請(qǐng)重新嘗試’ return render(request, 'app/login.html', { ’login_error_msg’: error_msg, ’next_url’: next_url, }) next_url = request.GET.get('next', ’’) # 檢查是否勾選了記住密碼功能 # password, check_value = ’’, ’’ # user_session = request.session.get(’user_info’, {}) # username = user_session.get(’username’, ’’) # print(user_session) #if request.session.get(’is_remember’): # password = user_session.get(’password’, ’’) # check_value = ’checked’ # print(username, password) return render(request, 'app/login.html', { ’next_url’: next_url, # ’user’: username, # ’password’: password, # ’check_value’: check_value })def logout(request): rep = redirect('/login/') # request.session.delete() # 登出,則刪除掉session中的某條數(shù)據(jù) if ’is_login’ in request.session: del request.session[’is_login’] return rep@check_logindef index(request): return render(request, 'autotest/index.html')
另附login.html部分代碼:
<form action='{% url ’login’ %}' method='post'> <h1>請(qǐng)使xxx賬戶登錄</h1> <div> <input type='text' name='username' placeholder='用戶' required='' value='{{ user }}' /> </div> <div> <input type='password' name='password' placeholder='密碼' required='' value='{{ password }}' /> </div> <div style='display: none;'> <input type='text' name='next_url' value='{{ next_url }}' /> </div> {% if login_error_msg %} <div id='error-msg'> <span style='color: rgba(255,53,49,0.8); font-family: cursive;'>{{ login_error_msg }}</span> </div> {% endif %} // 若設(shè)置了記住密碼功能 // <div style='float: left'> // <input type='checkbox' name='check_remember' {{ check_value }}/>記住密碼 // </div> <div> <button type='submit' style='float: initial; margin-right: 60px'>登錄</button> </div> </form>
總的來(lái)看,session也是利用了cookie,通過(guò)cookie生成的value的唯一性,從而在后端數(shù)據(jù)庫(kù)session表中找到這value對(duì)應(yīng)的數(shù)據(jù)。session的用法可以保存更多的用戶信息,并使這些信息不易被暴露。
總結(jié)
session和cookie都能實(shí)現(xiàn)記住用戶登錄狀態(tài)的功能,如果為了安全起見(jiàn),還是使用session更合適
以上這篇Django Session和Cookie分別實(shí)現(xiàn)記住用戶登錄狀態(tài)操作就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 利用CSS3新特性創(chuàng)建透明邊框三角2. PHP循環(huán)與分支知識(shí)點(diǎn)梳理3. 讀大數(shù)據(jù)量的XML文件的讀取問(wèn)題4. 解析原生JS getComputedStyle5. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)6. css代碼優(yōu)化的12個(gè)技巧7. 前端從瀏覽器的渲染到性能優(yōu)化8. ASP基礎(chǔ)入門第三篇(ASP腳本基礎(chǔ))9. ASP實(shí)現(xiàn)加法驗(yàn)證碼10. 無(wú)線標(biāo)記語(yǔ)言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁(yè)
