drf认证
- 参考网址
https://www.cnblogs.com/yangyi215/p/15041975.html
-
作用: 校验用户是否登录
-
书写步骤
- 写一个类,继承BaseAuthentication,重写类中的重写authenticate方法,认证的逻辑写在其中
- 如果认证通过,返回两个值,一个值最终给了Requet.user,另外一个值给了Requet.auth
- 如果认证失败,抛出异常,APIException或者AuthenticationFailed
ps:从源码中看出,如果有多个认证,要将返回有两个值的放到最后(认证流程见参考网址)
- 认证demo
### models.py
# 用户
class User(models.Model):
username = models.CharField(max_length=32)
password = models.CharField(max_length=32)
# token
class UserToken(models.Model):
token = models.CharField(max_length=64)
user = models.OneToOneField(to='User')
......
## your_app.auth.py
# 用户登录之前,校验token是否正确(即请求到LoginView之前,先经过这个认证类校验,通过了请求才到LoginView)
class MyAuthentication(BaseAuthentication):
# 须重写
def authenticate(self, request):
"""
如果认证通过,返回两个值 request.user和request.auth;
如果认证失败,抛出AuthenticationFailed异常
"""
# token = request.query_params.get('token')
token = request.data.get('token')
if token:
user_token = models.UserToken.objects.filter(token=token).first()
if user_token:
return user_token.user, token # 正确就返回user和token
else:
raise AuthenticationFailed('认证失败')
else:
raise AuthenticationFailed('请求地址中需要携带token')
## views
# 如果请求能来到这边,说明自定义 MyAuthentication 校验无误
class LoginView(APIView):
authentication_classes = [MyAuthentication,] # 局部配置
# uthentication_classes = []
def post(self, request):
username = request.data.get('username')
password = request.data.get('password')
user_obj = User.objects.filter(username=username, password=password).first()
if user_obj:
token_num = str(uuid.uuid4())
# 登录成功以后,更新token
UserToken.objects.update_or_create(defaults={'token': token_num}, user=user_obj)
return Response({'status': 100, 'msg': '登陆成功', 'token': token_num})
else:
return Response({'status': 101, 'msg': '用户名或密码错误'})
- 全局配置如下
......
# ---------DRF配置--------------------#
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": ["apps.tests.auth.MyAuthentication"]
}
......
class LoginView(APIView):
# authentication_classes = [MyAuthentication,] # 局部配置
authentication_classes = [] # 或者 authentication_classes 不写
标签:models,request,认证,token,user,password,DRF
From: https://www.cnblogs.com/qinganning/p/16998966.html