三大认证

三大认证

上次讲的 drf 还剩下 三大认证,当然也是从 APIView 的 dispatch 为入口。

    def dispatch(self, request, *args, **kwargs):
        """
        `.dispatch()` is pretty much the same as Django's regular dispatch,
        but with extra hooks for startup, finalize, and exception handling.
        """
        self.args = args
        self.kwargs = kwargs
        request = self.initialize_request(request, *args, **kwargs)
        self.request = request
        self.headers = self.default_response_headers  # deprecate?

        try:
            #这一步就做了三大认证,进去看源码。
            self.initial(request, *args, **kwargs)

            # Get the appropriate handler method
            if request.method.lower() in self.http_method_names:
                handler = getattr(self, request.method.lower(),
                                  self.http_method_not_allowed)
            else:
                handler = self.http_method_not_allowed

            response = handler(request, *args, **kwargs)

        except Exception as exc:
            response = self.handle_exception(exc)

        self.response = self.finalize_response(request, response, *args, **kwargs)
        return self.response

进入initial方法

    def initial(self, request, *args, **kwargs):
        """
        Runs anything that needs to occur prior to calling the method handler.
        """
        self.format_kwarg = self.get_format_suffix(**kwargs)

        # Perform content negotiation and store the accepted info on the request
        neg = self.perform_content_negotiation(request)
        request.accepted_renderer, request.accepted_media_type = neg

        # Determine the API version, if versioning is in use.
        version, scheme = self.determine_version(request, *args, **kwargs)
        request.version, request.versioning_scheme = version, scheme

        # Ensure that the incoming request is permitted
        
        #上面的都不要去管他,下面三条就是三大认证
        
        #认证模块:校验用户是否登录:登录用户、非法用户、游客
        self.perform_authentication(request)
        #权限模块:校验用户是否拥有权限:校验对象是登录用户和游客
        self.check_permissions(request)
        #频率模块:访问接口的次数在设定的时间范围内是否过快:配置访问频率,每次访问都要缓存计次,超次后需要等待的时间。
        self.check_throttles(request)

只有 认证模块和权限模块都通过了,才能访问接口,不需要第三个接口。 而且 认证模块和权限模块都是捆绑出现的。

那么是怎么调用这三个的?当然要通过配置了,看一下APIView的一堆属性

class APIView(View):

    # The following policies may be set at either globally, or per-view.
    renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
    parser_classes = api_settings.DEFAULT_PARSER_CLASSES
    #配置视图类的认证
    authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES
    #配置视图类的频率
    throttle_classes = api_settings.DEFAULT_THROTTLE_CLASSES
    #配置视图类的权限
    permission_classes = api_settings.DEFAULT_PERMISSION_CLASSES
    content_negotiation_class = api_settings.DEFAULT_CONTENT_NEGOTIATION_CLASS
    metadata_class = api_settings.DEFAULT_METADATA_CLASS
    versioning_class = api_settings.DEFAULT_VERSIONING_CLASS

    # Allow dependency injection of other settings to make testing easier.
    settings = api_settings

很明显上面三个配置都写在了 api_settings 里面,那么就是这里面看一下。

里面有很多配制,这里只给出关键的

DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication'
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
    ] 	

所以我们只要在局部配置了这个,也可以在项目下的 settings 里写,全局的就不起作用了,这就是我们可以自己写两个校验的基础。

这里先自己写一个之前的栗子

from rest_framework.views import APIView
from utils.response import APIResponse
class TestAPIView(APIView):
    def get(self, request, *args, **kwargs):
        print(request.user)  # AnonymousUser - 游客
        return APIResponse()

这里能答应出request.user,说明了什么,说明了能走到get方法里,也就是说通过了用户认证和权限认证,为什么即使没有登录之类的操作也可以?原因就是这就是游客登录,从后面分析源码可以看出。

现在就可以来看一下 认证模块的 SessionAuthentication 和 BasicAuthentication 都干了什么。

从配置中可以看出这两个都是在 rest_framework.authentication 下的,所以直接去看authentication。

发现在authentication.py文件下的四个类中,每个都有 authenticate 方法, 所以很显然是这个方法在完成校验。

拿出其中的一个类来看他的 authenticate方法

class BasicAuthentication(BaseAuthentication):
    """
    HTTP Basic authentication against username/password.
    """
    www_authenticate_realm = 'api'

    def authenticate(self, request):
        """
        Returns a `User` if a correct username and password have been supplied
        using HTTP Basic authentication.  Otherwise returns `None`.
        """
        # 从请求头中获取 认证字符串(auth)在后端叫做auth,前端就叫做 token
        auth = get_authorization_header(request).split()
		# 如果没有这个 auth,那就代表是游客登录,返回 none,在认证模块中 none就是游客。
        if not auth or auth[0].lower() != b'basic':
            return None
		
        # 如果有认证字符串,就一定会校验。
        #校验失败:抛出异常
        #校验成功:返回长度为 2 的元组,第一位是登录的user对象,具体看下面
        if len(auth) == 1:
            msg = _('Invalid basic header. No credentials provided.')
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) > 2:
            msg = _('Invalid basic header. Credentials string should not contain spaces.')
            raise exceptions.AuthenticationFailed(msg)
		# 加密
        try:
            auth_parts = base64.b64decode(auth[1]).decode(HTTP_HEADER_ENCODING).partition(':')
        except (TypeError, UnicodeDecodeError, binascii.Error):
            msg = _('Invalid basic header. Credentials not correctly base64 encoded.')
            raise exceptions.AuthenticationFailed(msg)

        userid, password = auth_parts[0], auth_parts[2]
        #最后返回这个authenticate_credentials方法的返回值
        return self.authenticate_credentials(userid, password, request)

    def authenticate_credentials(self, userid, password, request=None):
        """
        Authenticate the userid and password against username and password
        with optional request for context.
        """
        credentials = {
            get_user_model().USERNAME_FIELD: userid,
            'password': password
        }
        user = authenticate(request=request, **credentials)

        if user is None:
            raise exceptions.AuthenticationFailed(_('Invalid username/password.'))

        if not user.is_active:
            raise exceptions.AuthenticationFailed(_('User inactive or deleted.'))

        return (user, None)

这个类看完了再看一下下一个类

class SessionAuthentication(BaseAuthentication):
    """
    Use Django's session framework for authentication.
    """
	
    def authenticate(self, request):
        """
        Returns a `User` if the request session currently has a logged in user.
        Otherwise returns `None`.
        """

        # Get the session-based user from the underlying HttpRequest object
        #这个就直接从request里面去拿user
        user = getattr(request._request, 'user', None)

        # Unauthenticated, CSRF validation not required
        #拿的到就是用户登录,拿不到就是游客登录
        if not user or not user.is_active:
            return None
		
        #这里重新启用了csrf
        self.enforce_csrf(request)

        # CSRF passed with authenticated user
        return (user, None)

    def enforce_csrf(self, request):
        """
        Enforce CSRF validation for session based authentication.
        """
        check = CSRFCheck()
        # populates request.META['CSRF_COOKIE'], which is used in process_view()
        check.process_request(request)
        reason = check.process_view(request, None, (), {})
        if reason:
            # CSRF failed, bail with explicit error message
            raise exceptions.PermissionDenied('CSRF Failed: %s' % reason)


可以发现这些类都是继承 BaseAuthentication 的,我们看一下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

发现他的 authen 直接就是抛异常叫你重写 authenticate方法,这也就是我们自己写的基础。

现在为什么请求头不带认证字符串还能通过两层校验呢?第一层能通过已经知道了,返回了一个none,那么权限类他是怎么通过的。这个时候我们就要退出认证模块,去看一下权限模块了。

我们发现在之前settings里面配置的时候

DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication'
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
    ] 	

权限模块是一个 AllowAny ,看一下这个 AllowAny 做了什么。

class AllowAny(BasePermission):
    """
    Allow any access.
    This isn't strictly required, since you could use an empty
    permission_classes list, but it's useful because it makes the intention
    more explicit.
    """
   # 就这么一个方法,只要你能进来的,都有权限。如果把这个True改成false,之前的请求就会不能成功了,所有的请求都不成功。
    def has_permission(self, request, view):
        return True


看一下同个文件下的下一个类

class IsAuthenticated(BasePermission):
    """
    Allows access only to authenticated users.
    """
   # 当你是登录状态下,你的request.user就会有值,这里判断你是否有值,然后判断这个用户是否合法,都满足了,就返回一个 True,就有权限。
    def has_permission(self, request, view):
        return bool(request.user and request.user.is_authenticated)


这两个类都继承了 BasePermission 类。

稍微总结一下这两个模块工作原理。

"""
认证模块工作原理
1)继承BaseAuthentication类,重写authenticate方法
2)认证规则(authenticate方法实现体):
    没有携带认证信息,直接返回None => 游客
    有认证信息,校验失败,抛异常 => 非法用户
    有认证信息,校验出User对象 => 合法用户
"""

"""
权限模块工作原理
1)继承BasePermission类,重写has_permission方法
2)权限规则(has_permission方法实现体):
    返回True,代表有权限
    返回False,代表无权限
"""

那我们最主要的方式就是,如何让游客有权限无权限,如何让登陆用户有权限无权限,如何让登陆用户是某个角色才有权限无权限。

现在来实现一个必须要登录获取token之后,并且是超级用户才能实现的,获取所有非超级用户。

文件:

img

serializers:

from rest_framework import serializers
from rest_framework.serializers import ModelSerializer, ValidationError
from . import models
class UserModelSerializer(ModelSerializer):
    class Meta:
        model = models.User
        fields = ('username', 'email', 'mobile')



from django.contrib.auth import authenticate
class LoginModelSerializer(ModelSerializer):
    # username和password字段默认会走系统校验,而系统的post请求校验,一定当做增方式校验,所以用户名会出现 重复 的异常
    # 所以自定义两个字段接收前台的账号密码
    usr = serializers.CharField(write_only=True)
    pwd = serializers.CharField(write_only=True)
    class Meta:
        model = models.User
        #前端带的数据包里的 usr 和pwd
        fields = ('usr', 'pwd')
    #全局钩子,拿到 usr 和 pwd 
    def validate(self, attrs):
        usr = attrs.get('usr')
        pwd = attrs.get('pwd')
        try:
            #判断这个用户登录对不对
            user_obj = authenticate(username=usr, password=pwd)
        except:
            raise ValidationError({'user': '提供的用户信息有误'})

        # 拓展名称空间
        #这里的self,就是前面的 serializer 对象
        self.user = user_obj
        # 签发token
        self.token = _get_token(user_obj)

        return attrs


# 自定义签发token
# 分析:拿user得到token,后期还需要通过token得到user
# token:用户名(base64加密).用户主键(base64加密).用户名+用户主键+服务器秘钥(md5加密)
# eg: YWJj.Ao12bd.2c953ca5144a6c0a187a264ef08e1af1

# 签发算法:b64encode(用户名).b64encode(用户主键).md5(用户名+用户主键+服务器秘钥)
# 校验算法(认证类)与签发算法配套
"""
拆封token:一段 二段 三段
用户名:b64decode(一段)
用户主键:b64decode(二段)
碰撞解密:md5(用户名+用户主键+服务器秘钥) == 三段
"""

#token一定要是上面这种形式的 xxx.xxx.xxx
def _get_token(obj):
    import base64, json, hashlib
    from django.conf import settings
    #第一段,先把json字符串编码,然后在加密,在转成字符串
    t1 = base64.b64encode(json.dumps({'username': obj.username}).encode()).decode()
    #第二段,同理把pk也转了
    t2 = base64.b64encode(json.dumps({'pk': obj.id}).encode()).decode()
    #第三段,用md5加密,内容是一个字典,第三个东西是唯一的django的密钥
    t3_json = json.dumps({
        'username': obj.username,
        'pk': obj.id,
        'key': settings.SECRET_KEY
    })
    t3 = hashlib.md5(t3_json.encode()).hexdigest()
    #返回这种形式的token
    return '%s.%s.%s' % (t1, t2, t3)

authentications:

from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
class TokenAuthentication(BaseAuthentication):
    prefix = 'Token'
    def authenticate(self, request):
        # 拿到前台的token,必须要是 "token"+空格+"token内容" 形式,不然就不满足下面。
        auth = request.META.get('HTTP_AUTHORIZATION')
        # 没有返回None,有进行校验
        if not auth:
            return None
        auth_list = auth.split()

        if not (len(auth_list) == 2 and auth_list[0].lower() == self.prefix.lower()):
            raise AuthenticationFailed('非法用户')

        token = auth_list[1]

        # 校验算法
        user = _get_obj(token)
        # 校验失败抛异常,成功返回(user, token)
        return (user, token)

# 校验算法(认证类)与签发算法配套
"""
拆封token:一段 二段 三段
用户名:b64decode(一段)
用户主键:b64decode(二段)
碰撞解密:md5(用户名+用户主键+服务器秘钥) == 三段
"""
import base64, json, hashlib
from django.conf import settings
from api.models import User
def _get_obj(token):
    token_list = token.split('.')
    if len(token_list) != 3:
        raise AuthenticationFailed('token异常')
    username = json.loads(base64.b64decode(token_list[0])).get('username')
    pk = json.loads(base64.b64decode(token_list[1])).get('pk')

    md5_dic = {
        'username': username,
        'pk': pk,
        'key': settings.SECRET_KEY
    }

    if token_list[2] != hashlib.md5(json.dumps(md5_dic).encode()).hexdigest():
        raise AuthenticationFailed('token内容异常')

    user_obj = User.objects.get(pk=pk, username=username)
    return user_obj


""" 认证类的认证核心规则
def authenticate(self, request):
    token = get_token(request)
    try:
        user = get_user(token)  # 校验算法
    except:
        raise AuthenticationFailed()
    return (user, token)
"""

permissions:

# 自定义权限类
"""
权限模块工作原理
1)继承BasePermission类,重写has_permission方法
2)权限规则(has_permission方法实现体):
    返回True,代表有权限
    返回False,代表无权限
"""
from rest_framework.permissions import BasePermission
class SuperUserPermission(BasePermission):
    def has_permission(self, request, view):
        # print(request.user)
        # print(request.auth)

        return request.user and request.user.is_superuser




views

from rest_framework.generics import ListAPIView
from . import models, serializers
# 查看所有用户信息,前提:必须是登录的超级管理员
# 这里导入自己写的用户认证模块和权限模块
from utils.authentications import TokenAuthentication
from utils.permissions import SuperUserPermission
#使用视图家族的工具视图类,继承ListView,实现get方法群查
class UserListAPIView(ListAPIView):
    # 同电商网站,多接口是不需要登录的,少接口需要登录,使用在需要登录的接口中完成局部配置,进行局部接口校验
    #完成局部配置认证模块和权限模块,写了下面两句之后,将不会走drf的认证和权限模块
    authentication_classes = [TokenAuthentication]
    permission_classes = [SuperUserPermission]
	
    #先获取所有活跃的,非超级用户的用户queryset
    queryset = models.User.objects.filter(is_active=True, is_superuser=False).all()
    #送去序列化
    serializer_class = serializers.UserModelSerializer
	#强迫症非要自己格式化返回样式,于是重写get方法
    def get(self, request, *args, **kwargs):
        response = self.list(request, *args, **kwargs)
        return APIResponse(data=response.data)


# 登录接口:如果是超级管理员登录,返回一个可以交易出超级管理员的token字符串
# 只要有用户登录,就可以返回一个与登录用户相关的token字符串 => 返回给前台 => 签发token => user_obj -> token_str

from rest_framework.generics import GenericAPIView
class LoginAPIView(APIView):
    # 登录接口一定要做:局部禁用 认证 与 权限 校验,不然登录接口都进不去,玩毛
    authentication_classes = []
    permission_classes = []
    def post(self, request, *args, **kwargs):
        #送去反序列化
        serializer = serializers.LoginModelSerializer(data=request.data)
        # 重点:校验成功后,就可以返回信息,一定不能调用save方法,因为该post方法只完成数据库查操作
        # 所以校验会得到user对象,并且在校验过程中,会完成token签发(user_obj -> token_str)
        serializer.is_valid(raise_exception=True)
        return APIResponse(data={
            'username': serializer.user.username,
            #在反序列化类里面会生成一个user和token放在名称空间里,所以这里能返回
            'token': serializer.token
        })



posted @ 2019-12-01 08:42  chanyuli  阅读(549)  评论(0编辑  收藏  举报