目錄:
- SessionAuthentication驗證
- django 自帶登錄源碼分析
- postman測試結果
一、SessionAuthentication驗證
我們之前討論了BasicAuthentication、TokenAuthentication 驗證。我們現在來討論一下 Session 驗證。廢話不多說我們來看下,怎么使用session驗證的。當然我們都是在 局部環境下測試的,如果想要全局下測試,需要在Settings.py中 需要配置全局驗證。這個在TokenAuthentication驗證的博客中有。我就不多說了。
1.1、視圖
說明:導入session驗證,並且使用。再次聲明,這邊是局部配置,只對當前視圖有效。
....
from rest_framework.authentication import BasicAuthentication, TokenAuthentication, SessionAuthentication #導入SessionAuthentication驗證
from rest_framework.permissions import IsAuthenticated
# Create your views here.
class CartView(APIView):
# 基於什么登錄認證的
authentication_classes = [BasicAuthentication, TokenAuthentication, SessionAuthentication] #支持session驗證,三者任何一種驗證都可以,這邊我們主要用 Session驗證
# 只有登錄才能訪問
permission_classes = [IsAuthenticated]
def get(self, request, *args, **kwargs):
....
return JsonResponse(ctx)
哈哈,就這么簡單
二、django 自帶登錄源碼分析
小伙伴們有沒有發現一個問題,就是我們在訪問 admin 后台登錄,輸入用戶名密碼的時候,后台會自動生成 session。好啊,廢話不多少說了,直接看下源碼怎么寫的:
2.1、導入登錄模塊
from django.contrib.auth import login
2.2、查看登錄源碼
說明:Ctrl + login 走你 看看到底有啥:
def login(request, user, backend=None):
session_auth_hash = ''
if user is None:
user = request.user
if hasattr(user, 'get_session_auth_hash'):
session_auth_hash = user.get_session_auth_hash() #登錄的時候生成了一個session_id
if SESSION_KEY in request.session:
if _get_user_session_key(request) != user.pk or (
session_auth_hash and
not constant_time_compare(request.session.get(HASH_SESSION_KEY, ''), session_auth_hash)):
# To avoid reusing another user's session, create a new, empty
# session if the existing session corresponds to a different
# authenticated user.
request.session.flush()
else:
request.session.cycle_key()
....未完待續
2.3、登錄admin后台
說明:訪問 http://127.0.0.1:8000/admin。當然這個用戶是你用 python manage.py createsuperuser 創建出來的。

登錄成功后,我們來看下數據庫django_session:

三、postman測試結果
3.1、瀏覽器測試

3.2、postman測試結果
說明:postman測試的時候就要手動的把 cookie(上面瀏覽器生成的cookie) 輸入到請求 頭當中。

注意:這邊有一個要強調一個 只有 post、put、delete等方法才會收到 crf_token影響,get方法是不受影響的。
