Day 25 DRF认证相关
一、DRF认证功能介绍
只有认证通过的用户才能访问指定的url地址,比如:查询课程信息,需要登录之后才能查看,没有登录,就不能查看,这时候需要用到认证组件
二、源码分析
三、自定义认证类(重点)
1、使用
定义一个类,继承BaseAuthentication
class LoginAuth(BaseAuthentication):
def authenticate(self, request):
print(request.data)
username = request.data.get('username')
user = models.User.objects.filter(username=username).first()
token = models.UserToken.objects.filter(user__username=username).first()
if token:
return (user, token.token) # 一定要返回一个user对象,因为他是用的自己的request,后续需要用到user的地方,都是这里返回的
else:
raise AuthenticationFailed('您还没有登录!')xxxxxxxxxx class LoginAuth(BaseAuthentication): def authenticate(self, request): print(request.data) username = request.data.get('username') user = models.User.objects.filter(username=username).first() token = models.UserToken.objects.filter(user__username=username).first() if token: return (user, token.token) else: raise AuthenticationFailed('您还没有登录!')clas
重写authenticate方法
-局部使用和全局使用
-局部:在视图类中配置(只要配置了,就是登录以后才能访问,没配置,不用登录就能访问)
authentication_classes = [MyAuthen.LoginAuth, ]
-全局
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": ["app01.MyAuthen.LoginAuth", ]
}
-注意:
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
class SuperPermission(BasePermission):
def has_permission(self, request, view):
# Return `True` if permission is granted, `False` otherwise.
# 超级用户可以访问,除了超级用户以外,都不能访问
if request.user.user_type == '1': # 这里的user就是认证返回的user
return True
else:
return False
3 局部使用和全局使用
-在想局部使用的视图类上
permission_classes = [MyAuthen.SuperPermission]
-全局使用
REST_FRAMEWORK = {
"DEFAULT_PERMISSION_CLASSES": ["app01.MyAuthen.SuperPermission", ]
}
#在视图类中添加-局部禁用
permission_classes = []
六、权限功能局部使用和全局使用
1 使用方式
-在想局部使用的视图类上
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