码迷,mamicode.com
首页 > 其他好文 > 详细

RestFramework自定制之认证、权限、限制访问频率

时间:2018-02-18 14:13:36      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:ams   api   base   basic   display   response   get请求   import   elf   

 

认证

  所谓认证就是检测用户登陆与否,通常与权限对应使用。网站中都是通过用户登录后由该用户相应的角色认证以给予对应的权限。

自定制认证规则的重点是继承内置的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自定制之认证、权限、限制访问频率

标签:ams   api   base   basic   display   response   get请求   import   elf   

原文地址:https://www.cnblogs.com/zhuminghui/p/8452733.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!