day84

认证组件

源码分析方法

首先我们来到views下的dispatch下,因为每次进入视图函数是由dispatch进行路由分发

绿线标注:rest'frame'work对于request的重新包装(包装后在视图函数可以直接request.data取值,并且可以直接取出JSON格式数据)

红线标注:就是认证时要进入的方法

(首先我们需要去查看一下他是如何包装的request)

来到initialize_request发现有一个get_authenticators

我们发现该方法就是将一个列表中的方法加括号实例化到一个列表中

他会遍历我们视图类中的authentication_classes

然后我们回到dispatch,进入initial方法

红线标注:我们今天要说的就是认证,所以进入self.perform_authentication(request)

可以发现来到该方法下,我们发现只有一个request.user,所以我们应该在request方法下找到user

 进入request的user

然后user中调用self._authenticate()方法

这里会执行前面我们所找到的authenticators并且执行

认证组件使用:

 写一个类:# 函数名一定要叫authenticate,接收必须两个参数,第二个参数是request对象

from rest_framework.exceptions import APIException
from rest_framework.authentication import BaseAuthentication

# 自定义的加密了一个token
def get_token(pwd):
    s1 = ""
    add = 0
    s2 = pwd.split('|')[1]
    li = pwd.split('|')[0].split('-')
    for i in li:
        s1 += chr(int(i) - add)
        add += 1
    return s1, s2


class Auth(BaseAuthentication):
    # 源码中最后会调用该对象下的authenticate方法,所以名字必须是authenticate
    def authenticate(self, request):
        token = request.query_params.get('token')
        if token:
            s1, s2 = get_token(token)
            if s1 == s2:
                return None
        raise APIException('请先登录')
View Code

局部使用:

  -在视图类中加一行:

     -authentication_classes = [LoginAuth, ]

-全局使用

-在setting中配置:
		REST_FRAMEWORK={
			'DEFAULT_AUTHENTICATION_CLASSES':['app01.MyAuth.LoginAuth',]
			}
		-局部禁用:				
			-在视图类中加一行:
			-authentication_classes = []

权限控制

from rest_framework.permissions import BasePermission


class permission(BasePermission):
    # 源码中若返回False,则会有一个mssage属性,也就是错误提示信息
    message = "您的权限不够"
    # 源码中最后会调用该对象下的has_permission方法,所以名字必须是has_permission
    def has_permission(self, request, view):
        user_type = request.user.user_type
        if user_type == "2":
            return True
View Code

-局部使用

    -在视图类中加一行:

-permission_classes = [LoginAuth, ]

-全局使用

-在setting中配置
					REST_FRAMEWORK={
						'DEFAULT_PERMISSION_CLASSES':['app01.MyAuth.UserPermission',]
					}
				-局部禁用
					-在视图类中加一行:
					-permission_classes = [ ]

  

原文地址:https://www.cnblogs.com/yaoxiaofeng/p/10112005.html