Django的RBAC认证和权限

1.认证

python 复制代码
import jwt
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from rbac import settings


class User(object):
    def __init__(self, id, username, role, exp):
        self.id = id
        self.username = username
        self.role = role
        self.exp = exp



class RbacAuthentication(BaseAuthentication):
    def authenticate(self, request):
        # 1. 获取jwt token
        jwt_token = request.query_params.get("token")
        if not jwt_token:
            return AuthenticationFailed("认证失败")
        # 2.校验jwt token合法性
        try:
            verified_payload = jwt.decode(jwt_token, settings.SECRET_KEY, algorithms="HS256")
            print(verified_payload)
        except Exception as e:
            raise AuthenticationFailed("认证失败")

        # 3. 返回
        user = User(**verified_payload)
        return user, jwt

    def authenticate_header(self, request):
        return "API"

2.权限

python 复制代码
from rest_framework.permissions import BasePermission

from rbac import settings


class RbacPermission(BasePermission):
    def has_permission(self, request, view):
        # 1.当前用户角色
        user_role = request.user.role
        # 2.获取当前权限
        user_total_permission = settings.PERMISSION.get(user_role)

        # 3.当前用户请求的路由信息
        router_name = request.resolver_match.view_name
        method = request.method.lower()
        method_list = user_total_permission.get(router_name)
        if not method_list:
            return False
        if method not in method_list:
            return False
        return True

3.全局配置

python 复制代码
REST_FRAMEWORK = {
    "UNAUTHENTICATED_USER": None,
    "UNAUTHENTICATED_TOKEN": None,
    "DEFAULT_AUTHENTICATION_CLASSES": ["utils.auth.RbacAuthentication"],
    "DEFAULT_PERMISSION_CLASSES": ["utils.permission.RbacPermission"]
}
相关推荐
中国lanwp4 分钟前
Spring Boot 中使用 Lombok 进行依赖注入的示例
java·spring boot·后端
胡萝卜的兔4 分钟前
golang -gorm 增删改查操作,事务操作
开发语言·后端·golang
屁股割了还要学8 分钟前
快速过一遍Python基础语法
开发语言·python·学习·青少年编程
掘金码甲哥2 小时前
Golang 文本模板,你指定没用过!
后端
你怎么知道我是队长3 小时前
python-enumrate函数
开发语言·chrome·python
大熋3 小时前
Playwright Python 教程:网页自动化
开发语言·python·自动化
lwb_01183 小时前
【springcloud】快速搭建一套分布式服务springcloudalibaba(四)
后端·spring·spring cloud
A7bert7773 小时前
【YOLOv8-obb部署至RK3588】模型训练→转换RKNN→开发板部署
linux·c++·人工智能·python·yolo
cdg==吃蛋糕4 小时前
selenium 使用方法
开发语言·python
Y1nhl4 小时前
力扣_二叉树的BFS_python版本
python·算法·leetcode·职场和发展·宽度优先