认证组件Authentication的配置方式一
在配置文件中配置全局认证方案
- 首先可以在目录 /rest_framework/settings.py 下,找到认证组件配置
- 然后将配置信息,添加到项目主应用的settings.py中,但是这样是全局配置
- 示例代码
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication', # session认证
'rest_framework.authentication.BasicAuthentication', # 基本认证
#当然这儿也可以写自己定义好的类
#因为全局配置太过于粗暴,如果某些视图函数不需要权限认证的话,可以加上一个 authentication_classes = [ ] 等于一个空列表
)
}
认证组件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:
# if token != request.user.token:
raise AuthenticationFailed({"code": 1000, "data": "认证失败"})
else:
# return request.user,token
return user_obj, token
def authenticate_header(self, request):
pass
##视图函数POST写法
#POST为登录方法,不用认证,只需要验证用户名和密码
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}})
##视图函数GET方法
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),表示在当前认证类完成后,如果后面还有认证类,也不会继续认证了
Original: https://www.cnblogs.com/zhiqianggege/p/16221734.html
Author: 志强爱璇璇
Title: drf –用户认证组件Authentication
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/596288/
转载文章受原作者版权保护。转载请注明原作者出处!