1. 程式人生 > >RestFramework自定制之認證、權限、限制訪問頻率

RestFramework自定制之認證、權限、限制訪問頻率

[1] eal val def app http asi col basic

認證

  所謂認證就是檢測用戶登陸與否,通常與權限對應使用。網站中都是通過用戶登錄後由該用戶相應的角色認證以給予對應的權限。

自定制認證規則的重點是繼承內置的BaseAuthentication類,重寫其authenticate()方法

方式一:通過url傳參進行認證

技術分享圖片
from django.conf.urls import url, include
from app01.views import TestView

urlpatterns = [
    url(r^test/, TestView.as_view()),
]
ulrs.py 技術分享圖片
from rest_framework.views import
APIView from rest_framework.response import Response from rest_framework.authentication import BaseAuthentication from rest_framework.request import Request from rest_framework import exceptions ######偽造的數據庫中存有的token######## token_list = [ sfsfss123kuf3j123, asijnfowerkkf9812, ] ######自定制的認證規則的類,必須繼承BaseAuthentication#####
class TestAuthentication(BaseAuthentication): def authenticate(self, request): """ 用戶認證,如果驗證成功後返回元組: (用戶,用戶Token) :param request: :return: None,表示跳過該驗證; 如果跳過了所有認證,默認用戶和Token和使用配置文件進行設置 self._authenticator = None if api_settings.UNAUTHENTICATED_USER: self.user = api_settings.UNAUTHENTICATED_USER() else: self.user = None if api_settings.UNAUTHENTICATED_TOKEN: self.auth = api_settings.UNAUTHENTICATED_TOKEN() else: self.auth = None (user,token)表示驗證通過並設置用戶名和Token; AuthenticationFailed異常
""" val = request.query_params.get(token) if val not in token_list: raise exceptions.AuthenticationFailed("用戶認證失敗") return (登錄用戶, 用戶token) def authenticate_header(self, request): """ Return a string to be used as the value of the `WWW-Authenticate` header in a `401 Unauthenticated` response, or `None` if the authentication scheme should return `403 Permission Denied` responses. """ # 驗證失敗時,返回的響應頭WWW-Authenticate對應的值 pass #####視圖函數,必須繼承APIView##### class TestView(APIView): authentication_classes = [TestAuthentication, ]#中括號中寫入定義了認證規則的類 permission_classes = []#這是權限規則,下文會進行詳述 #只有通過了上述的規則,才能以下執行視圖函數 def get(self, request, *args, **kwargs): print(request.user) print(request.auth) return Response(GET請求,響應內容) def post(self, request, *args, **kwargs): return Response(POST請求,響應內容) def put(self, request, *args, **kwargs): return Response(PUT請求,響應內容)
views.py

方式二:通過請求頭認證

技術分享圖片
from django.conf.urls import url, include
from app01.views import TestView

urlpatterns = [
    url(r^test/, TestView.as_view()),
]
ulrs.py 技術分享圖片
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.authentication import BaseAuthentication
from rest_framework.request import Request
from rest_framework import exceptions


#####自定制認證規則的類#####
class TestAuthentication(BaseAuthentication):
    def authenticate(self, request):
        """
        用戶認證,如果驗證成功後返回元組: (用戶,用戶Token)
        :param request: 
        :return: 
            None,表示跳過該驗證;
                如果跳過了所有認證,默認用戶和Token和使用配置文件進行設置
                self._authenticator = None
                if api_settings.UNAUTHENTICATED_USER:
                    self.user = api_settings.UNAUTHENTICATED_USER()
                else:
                    self.user = None
        
                if api_settings.UNAUTHENTICATED_TOKEN:
                    self.auth = api_settings.UNAUTHENTICATED_TOKEN()
                else:
                    self.auth = None
            (user,token)表示驗證通過並設置用戶名和Token;
            AuthenticationFailed異常
        """
        import base64
        auth = request.META.get(HTTP_AUTHORIZATION, b‘‘)#獲取請求頭
        if auth:
            auth = auth.encode(utf-8)#將bytes類型編碼成utf-8
        auth = auth.split()
        if not auth or auth[0].lower() != bbasic:
            raise exceptions.AuthenticationFailed(驗證失敗)
        if len(auth) != 2:
            raise exceptions.AuthenticationFailed(驗證失敗)
        username, part, password = base64.b64decode(auth[1]).decode(utf-8).partition(:)
        if username == Damon and password == 123:
            return (登錄用戶, 用戶token)
        else:
            raise exceptions.AuthenticationFailed(用戶名或密碼錯誤)

    def authenticate_header(self, request):
        """
        Return a string to be used as the value of the `WWW-Authenticate`
        header in a `401 Unauthenticated` response, or `None` if the
        authentication scheme should return `403 Permission Denied` responses.
        """
        return Basic realm=api


class TestView(APIView):
    authentication_classes = [TestAuthentication, ]#中括號中放入自定制的類,可放入多個
    permission_classes = []

    def get(self, request, *args, **kwargs):
        print(request.user)
        print(request.auth)
        return Response(GET請求,響應內容)

    def post(self, request, *args, **kwargs):
        return Response(POST請求,響應內容)

    def put(self, request, *args, **kwargs):
        return Response(PUT請求,響應內容)
views.py

RestFramework自定制之認證、權限、限制訪問頻率