基于django rest framework做认证组件

先导入要用到的类

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)

注意:

  • 认证成功返回元组,obj.user是固定的,后面的username取决于你的用户变中的用户名字段;

  • 认证失败,抛异常,返回AuthenticationFailed;

  • 匿名用户,返回None.

使用:你要访问某个页面,需要做登录认证时,就把它加在相应的类下面。  

 

 

猜你喜欢

转载自www.cnblogs.com/gaoya666/p/9149657.html
今日推荐