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"]
}
相关推荐
怒放的生命19916 分钟前
代码知识库 RAG 问答系统 —— 从 0 到 1 实现教程
python·状态模式·fastapi·全栈开发·ai agent应用开发
geovindu29 分钟前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
码事漫谈34 分钟前
黄仁勋的来时路
后端
bai2731 小时前
path.join('C:\a', '\b') 给我 C:\a\b,path.resolve 给 C:\b:Windows 上 51 行路径实测
javascript·后端
hackhase1 小时前
Django 多表数据整合:7 张异构表如何收敛成 4 类页面
后端·mysql
fengkai45451 小时前
Python运维
运维·python·监控·psutil·ipy
Fancy.7611 小时前
:Python条件与循环语句学习总结
python
Wellijohn3 小时前
Python 容器选型实测:list.insert(0) 慢 925 倍,in 慢 6000 倍
python
新*3 小时前
标题全变成一级?靠编号规律找回章节边界
python·正则表达式·pdf解析·文本处理
Cosolar3 小时前
需求做完了,经验归零了:Agent 真正缺的是第二条闭环
人工智能·后端·agent