一、自定义认证类
#定义一个类继承BaseAuthentication,重写了authenticate方法
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from app01 import models
class LoginAuth(BaseAuthentication):
def authenticate(self,request):
# token = request.GET.get('token') # 从浏览器中获取
token = request.META['HTTP_TOKEN'] #从请求头中获取
print(token)
res = models.UserToken.objects.filter(token=token).first()
if res:
return (res.user,token) #self.user, self.auth = user_auth_tuple
else:
raise AuthenticationFailed('你没有登陆')
#注意:1、认证类中,认证通过会返回一个元组,有两个值,第一个值会给request.user,第二个值会给request.auth
#2、认证类可以配置多个,按照从前向后的顺序执行,如果前面有返回值,认证就不再继续了
二、认证功能局部使用和全局使用
#1、全局使用(所有接口,都需要登陆才能访问)
-在配置文件中
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": ["app01.MyAuthen.LoginAuth", ]
}
#2、局部使用
-在想局部使用的视图类上
authentication_classes = [MyAuthen.LoginAuth,]
#3、局部禁用
-在想禁用的视图类上
authentication_classes = []
三、自定义权限功能
#1、登录成功以后,超级用户可以干某些事,普通用户不能干---》超级用户可以查看某些接口,普通用户不能查看
#2、定义一个类继承BasePermission,重写has_permission
from rest_framework.permissions import BasePermission
class SuperPermission(BasePermission):
def has_permission(self, request, view):
if request.user.user_type == 2:
return True
else:
return False
四、权限功能局部使用和全局使用
#在想局部使用的视图类上
permission_classes = [MyAuthen.SuperPermission]
#全局使用
REST_FRAMEWORK = {
"DEFAULT_PERMISSION_CLASSES": ["app01.MyAuthen.SuperPermission", ]
}
#局部禁用
permission_classes = []
五、内置的权限和认证类
# 内置认证类
from rest_framework.exceptions import AuthenticationFailed
# 内置权限类
from rest_framework.permissions import BasePermission