zoukankan      html  css  js  c++  java
  • drf框架中认证与权限工作原理及设置

    0909自我总结

    drf框架中认证与权限工作原理及设置

    一.概述

    1.认证

    工作原理

    • 返回None => 游客
    • 返回user,auth => 登录用户
    • 抛出异常 => 非法用户

    前台对于用户信息进行的判断

    1)如果前台没有携带认证信息,直接定义为游客

    2)如果前台携带了认证信息并认证通过,定位为登录用户,将登录的用户user对象保存在 requset.user 中

    3)如果前台携带了认证信息但没有认证通过,一般都定义为游客

    4 ) 可以自定义为非法用户,抛出 认证失败 异常,但是不建议直接操作,可以交给权限组件进一步处理rest_framework.exceptions 的 AuthenticationFailed

    参数

    • BasicAuthentication : 基本认证

    • SessionAuthentication : session认证

    2.权限

    工作原理

    • 返回False => 没有权限,将信息返回给前台
    • 返回True => 拥有权限,进行下一步认证(频率认证)

    相关设置

    • AllowAny:允许所有用户
    • IsAuthenticated:只允许登录用户
      • 必须request.user和request.user.is_authenticated都通过
    • IsAuthenticatedOrReadOnly:游客只读,登录用户无限制
      • get、option、head 请求无限制
      • 前台请求必须校验 request.user和request.user.is_authenticated
    • IsAdminUser:是否是后台用户
      • 校验 request.user和request.user.is_staff is_staff(可以登录后台管理系统的用户)

    二.局部设置

    即在我们自定义的视图类开头设置

    # 认证 下面不一定是[],也可以()就是需要在数组当中,多个类用,隔开
    # 局部取消认证组件:authentication_classes = []
    # 区别启用认证组件:authentication_classes = [认证类们] 
    # 填写的参数BasicAuthentication,SessionAuthentication 
    
    
    # 权限
    # 局部取消权限组件:permission_classes = []
    # 区别启用权限组件:permission_classes = [权限类们]
    # 填写的参数AllowAny
    

    from rest_framework.authentication import SessionAuthentication, BasicAuthentication
    from rest_framework.views import APIView
    from rest_framework.permissions import IsAuthenticated
     
    class 类名(APIView):
        authentication_classes = (SessionAuthentication, BasicAuthentication)
        permission_classes = [IsAuthenticated,]
    	...........
    

    三.全局设置

    setting中设置

    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': [
            # django默认session校验:校验规则 游客 及 登录用户
            'rest_framework.authentication.SessionAuthentication',
            'rest_framework.authentication.BasicAuthentication',
        ],
        'DEFAULT_PERMISSION_CLASSES': [
            # 'rest_framework.permissions.AllowAny',
            # 全局配置:一站式网站(所有操作都需要登录后才能访问)
            # 'rest_framework.permissions.IsAuthenticated',
        ],
    }
    

    四.失败返回的内容

    • 401 Unauthorized 未认证
    • 403 Permission Denied 权限被禁止
  • 相关阅读:
    01 mybatis框架整体概况(2018.7.10)-
    第一课(2018.7.10)
    JavaEE 企业级分布式高级架构师课程_汇总贴
    5-1条件运算符 & 5-2
    5-3运算符的优先级
    4-3逻辑非运算符及案例 & 4-4
    4-1逻辑与运算符介绍 & 4-2逻辑或运算符介绍
    3-3if-else条件结构 & 3-4 & 3-5
    3-2if条件结构
    3-1关系运算符
  • 原文地址:https://www.cnblogs.com/pythonywy/p/11492877.html
Copyright © 2011-2022 走看看