0909自我總結
drf框架中認證與權限工作原理及設置
一.概述
1.認證
工作原理
- 返回None => 游客
- 返回user,auth => 登錄用戶
- 拋出異常 => 非法用戶
前台對於用戶信息進行的判斷
1)如果前台沒有攜帶認證信息,直接定義為游客
2)如果前台攜帶了認證信息並認證通過,定位為登錄用戶,將登錄的用戶user對象保存在 requset.user 中
3)如果前台攜帶了認證信息但沒有認證通過,一般都定義為游客
4 ) 可以自定義為非法用戶,拋出 認證失敗 異常,但是不建議直接操作
,可以交給權限組件進一步處理rest_framework.exceptions 的 AuthenticationFailed
參數
-
BasicAuthentication : 基本認證
-
SessionAuthentication : session認證
2.權限
工作原理
- 返回False => 沒有權限,將信息返回給前台
- 返回True => 擁有權限,進行下一步認證(頻率認證)
相關設置
- AllowAny:允許所有用戶
- IsAuthenticated:只允許登錄用戶
- 必須request.user和request.user.is_authenticated都通過
- IsAuthenticatedOrReadOnly:游客只讀,登錄用戶無限制
- get、option、head 請求無限制
- 前台請求必須校驗 request.user和request.user.is_authenticated
- IsAdminUser:是否是后台用戶
- 校驗 request.user和request.user.is_staff is_staff(可以登錄后台管理系統的用戶)
二.局部設置
即在我們自定義的視圖類開頭
設置
# 認證 下面不一定是[],也可以()就是需要在數組當中,多個類用,隔開
# 局部取消認證組件:authentication_classes = []
# 區別啟用認證組件:authentication_classes = [認證類們]
# 填寫的參數BasicAuthentication,SessionAuthentication
# 權限
# 局部取消權限組件:permission_classes = []
# 區別啟用權限組件:permission_classes = [權限類們]
# 填寫的參數AllowAny
如
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
class 類名(APIView):
authentication_classes = (SessionAuthentication, BasicAuthentication)
permission_classes = [IsAuthenticated,]
...........
三.全局設置
在setting
中設置
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
# django默認session校驗:校驗規則 游客 及 登錄用戶
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
# 'rest_framework.permissions.AllowAny',
# 全局配置:一站式網站(所有操作都需要登錄后才能訪問)
# 'rest_framework.permissions.IsAuthenticated',
],
}
四.失敗返回的內容
- 401 Unauthorized 未認證
- 403 Permission Denied 權限被禁止