Djangorestframework下的自定义登录认证

tech2022-10-04  71

Djangorestframework下的自定义登录认证

1.自定义认证组件
from rest_framework.authentication import BaseAuthentication from rest_framework.exceptions import ParseError class Authentication(BaseAuthentication): #自定义HTTP状态码 ParseError.status_code = status.HTTP_200_OK def authenticate(self, request): uid = request.META.get("HTTP_UID") token = request.META.get("HTTP_TOKEN") List = UserToken.objects.filter(status=1,uid=uid,token=token).first() if List: #设置token有效值 delta = nowtime -List.createDate if delta.days >= 7: List.status=0 List.save() raise ParseError({"code": 3, "msg": "登录已失效,请刷新页面后登录", "result": ""}) else: return (uid, token) else: raise ParseError({"code": 3, "msg": "验证错误,请刷新页面后登录", "result": ""})
2.settings设置
REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), # token验证组件 "DEFAULT_AUTHENTICATION_CLASSES": ["users.auth.Authentication", ] }

开始试一下吧!

最新回复(0)