先导入要用到的类python
from rest_framework.authentication import BaseAuthentication from rest_framework.exceptions import AuthenticationFailed
# 登陆认证 class LuffyAuth(BaseAuthentication): def authenticate(self, request): # request._request ret = {"code": 1000, "data": None} token = request.query_params.get("token") obj = models.UserAuthToken.objects.filter(token=token).first() if not obj: raise AuthenticationFailed({'code':1001,'error':'认证失败'}) return (obj.user.username,obj)
注意:spa
认证成功返回元组,obj.user是固定的,后面的username取决于你的用户变中的用户名字段;rest
认证失败,抛异常,返回AuthenticationFailed;code
匿名用户,返回None.blog
使用:你要访问某个页面,须要作登陆认证时,就把它加在相应的类下面。 token