认证组件Authentication的配置方式一
在配置文件中配置全局认证方案
- 首先可以在目录 /rest_framework/settings.py 下,找到认证组件配置
- 然后将配置信息,添加到项目主应用的settings.py中,但是这样是全局配置
- 示例代码
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
)
}
认证组件Authentication的配置方式二
在每个视图类中,通过设置authentication_classess类属性来设置
示例代码:
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.views import APIView
class ExampleView(APIView):
authentication_classes = [SessionAuthentication, BasicAuthentication]
def get(self,request):
pass
认证结果
认证失败会有两种可能的返回值,这个需要我们配合权限组件来使用:
- 401 Unauthorized 未认证
- 403 Permission Denied 权限被禁止
三、自定义认证逻辑,以及自定义认证失败的错误信息
- 首先,我们可以自己定义一个认证组件,来继承drf写好的认证组件类:BaseAuthentication
- 重写 BaseAuthentication 类的 authenticate()方法,来实现具体的逻辑,以及重新
- authenticate()方法在认证失败时,可以通过 drf的认证失败类AuthenticationFailed,来自定义抛出的错误信息
- authenticate()方法认证成功时,返回一个元祖,元祖的第一个元素赋值给request.user,元祖第二个元素赋值给request.auth,因此,我们在编写逻辑的时候,要注意返回的值给放对位置
示例代码:
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from student.models import Student
class Auth(BaseAuthentication):
def authenticate(self, request):
token = request.query_params.get('token')
if not token:
raise AuthenticationFailed({"code": 1000, "data": "认证失败"})
user_obj = Student.objects.filter(token=token).filter()
if not user_obj:
raise AuthenticationFailed({"code": 1000, "data": "认证失败"})
else:
return user_obj, token
def authenticate_header(self, request):
pass
def post(self,request,*args,**kwargs):
username= request.data.get('username')
password = request.data.get('password')
user_obj = Student.objects.filter(username=username,password=password).first()
if not user_obj:
return Response({"code":1000,'data':"用户名或密码错误"})
token = str(uuid.uuid4())
user_obj.token = token
user_obj.save()
return Response({"code":0,"data":{"touck":token,"name":username}})
class StudentViewSet(APIView):
authentication_classes = [Auth, ]
def get(self, request, *args, **kwargs):
print(request.user)
print(request.auth)
return Response("ok")
最后,需注意,认证类的 authenticate()方法的 3种返回值:
- 返回 None ,表示如果存在多个认证类,返回None可以执行下一个认证类
- 返回 (None,None) ,表示该认证类不生效,也就是不执行该认证类的效果
- 返回 (user,auth),表示在当前认证类完成后,如果后面还有认证类,也不会继续认证了
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通