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"]
}
相关推荐
zavoryn5 分钟前
后端接入 AI Agent:Tool Calling 网关、幂等与审计日志实战
后端·架构
春日见5 分钟前
5分钟入门强化学习之动态规划算法与实现
大数据·人工智能·python·算法·机器学习·计算机视觉
DeniuHe37 分钟前
sklearn 中所有交叉验证数据集划分方式完整总结
人工智能·python·sklearn
DeniuHe41 分钟前
sklearn中不同交叉验证方法的场景适配
人工智能·python·sklearn
swipe1 小时前
混合检索 RAG 的工程化实践:不是多查几路,而是把召回、重排和上下文预算管好
后端·langchain·llm
隐于花海,等待花开1 小时前
16.Python 常用第三方库概览 深度解析
python
我材不敲代码1 小时前
Python 函数核心:位置参数与关键字参数详解
java·前端·python
风落无尘1 小时前
第十一章《对齐与安全》 完整学习资料
python·安全·机器学习
uzong1 小时前
分布式下的系统,什么是算是好的架构设计
后端·架构
Kratzdisteln1 小时前
【无标题】
前端·python