DRF - 内置认证类

在 rest framework 的 authentication.py 中

BaseAuthentication 是我们自己写认证类要继承的

class BaseAuthentication:
    """
    All authentication classes should extend BaseAuthentication.
    """

    def authenticate(self, request):
        """
        Authenticate the request and return a two-tuple of (user, token).
        """
        raise NotImplementedError(".authenticate() must be overridden.")

    def authenticate_header(self, request):
        """
        Return a string to be used as the value of the `WWW-Authenticate`
        header in a `401 Unauthenticated` response, or `None` if the
        authentication scheme should return `403 Permission Denied` responses.
        """
        pass

authenticate 是我们自己写认证类的时候要重写的,不然会直接报错,该方法返回一个元组 (user, token)

authenticate_header 是认证失败后返回的响应头

BasicAuthentication 可用于浏览器实现登录认证

其中的 authenticate 方法:

对源码进行如下修改:

访问:

 

 浏览器将用户名密码进行 BASE64 加密,加密后加到请求头 HTTP_AUTHORIZATION 中,然后发给后端

后端则根据请求头进行获取数据,拆分,解密,对比数据

posted @ 2021-01-14 21:45  Sch01aR#  阅读(140)  评论(0编辑  收藏  举报