Authencation

用户认证

token ( 前后端分离 )

cookie & session (前后端不分离)

token = models.UUIDField()
import uuid
token = uuid.uuid4()
 
class TokenAuthencate(BaseAuthentication):
    def authenticate(self, request):
        token = request.META.get('HTTP_AUTHENTICATION')
        user_obj = models.User.objects.filter(token=token).first()
        if not user_obj:
            raise AuthenticationFailed('无效token')
 
        return user_obj, token
 

aaa

继承 BaseAuthentication 类,并重写authenticate方法

三种操作:

  1. 抛出异常,后续不执行 from rest_framework.execptions import AuthenticationFailed

    raise AuthenticationFailed ({'code':xxx,'msg':xxx})
    
  2. return 一个元组 (1,2) ,认证通过 ,以后 request.user 就是 1 ,request.auth 就是2

  3. None 这个认证什么也不做 干下一个认证

return (payload.token)

原文地址:https://www.cnblogs.com/tangshuo/p/12744446.html