drf—三大认证

1、authenticators

认证组件

作用:用于校验客户端身份,校验token

1.1 认证组件类

1、drf默认配置类

# 提供了4种,如下
BasicAuthentication
SessionAuthentication
TokenAuthentication
RemoteUserAuthentication

'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication'
    ],

2、配置jwt认证类

# settings.py文件中
# 除了登陆之外,基本上所有的请求都需要认证,所以配置在全局中
'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication'
    ],

3、自定义认证类

# 自建一个py文件,定义认证类,结构如下:
class MyAuthentication(BasicAuthentication):
    def authenticate(self, request):
        '''
        1	从请求头拿到token(HTTP_AUTHORIZATION)
        2	需要注意,前端发token时,需要按照后端校验的规则重构token,与认证组件的校验规则相关
       	3	没有token,就返回None,token的格式不对,也返回None,代表用户为游客
        4	有token,进入校验
        		不通过,抛出异常AuthenticationFailed()
        		通过,返回元组(user, token),为合法用户
        '''
        return super().authenticate(request)
    

1.2 配置使用

1、全局配置:一般在全局中配置认证组件

2、局部配置:给不需要认证的请求函数进行局部配置,一般为login

authentication_classes = ['类名']

2、permissions

权限组件

一般用于控制当前登陆用户的权限

2.1 权限组件类

1、drf默认配置类

# drf提供了一共4种,如下:
IsAdminUser, IsAuthenticated, IsAuthenticatedOrReadOnly, AllowAny

# 其中作为默认配置的是
'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
    ],

2、自定义权限类

'''
1	所有的权限类,都继承于BasePermission
2	方法has_permission(self, request, view)的返回值决定是否拥有该权限
'''
class VipPermission(BasePermission):
    def has_permission(self, request, view):
        for group in request.user.groups.all():
            print(group.name)
            if group.name.lower() == 'vip':
                return True
        return False

2.2 配置使用

权限类,一般在局部进行配置,根据请求不同,对用户进行权限限制

permission_classes = [permissions.VipPermission]

3、throttles

频率组件

一般用于控制用户访问接口的频率

3.1 频率组件类

1、drf默认配置类

# drf一共提供了三种频率控制类,如下
AnonRateThrottle  # 匿名用户的频率控制
UserRateThrottle  # 合法用户的频率控制
ScopedRateThrottle  # 

# 其中作为默认配置的是空
'DEFAULT_THROTTLE_CLASSES': [],

2、自定义频率类

'''
1	都继承于SimpleRateThrottle
2	都是通过scope来反射获取配置文件中的频率设置
3	get_cache_key(self, request, view)返回值来确定频率控制
		返回None:不受频率控制
		返回self.cache_format % {
            'scope': self.scope,
            'ident': request.user.mobile
        }
        其中,scope可以反射配置中设置的频率,ident是作为频率计算的依据
'''

class MobileRateThrottle(SimpleRateThrottle):
    scope = 'mobile'
    def get_cache_key(self, request, view):
        if not request.user.is_authenticated or not request.user.mobile:
            return None
        return self.cache_format % {
            'scope': self.scope,
            'ident': request.user.mobile
        }


3.2 配置使用

一般在局部进行配置,根据不同请求,设置频率认证

throttle_classes = [throttles.MobileRateThrottle]


我的博客即将同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=2akngr3ftihw4


posted @ 2020-01-06 19:39  W文敏W  阅读(451)  评论(0编辑  收藏  举报