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"]
}
相关推荐
右手嘚温暖4 小时前
分布式事务Seata、LCN的原理深度剖析
spring boot·分布式·后端·spring·spring cloud·中间件·架构
麦兜*6 小时前
Spring Boot集成方案 + Elasticsearch向量检索,语义搜索核弹
java·spring boot·python·spring·elasticsearch·spring cloud·系统架构
仪器科学与传感技术博士6 小时前
python:讲懂决策树,为理解随机森林算法做准备,以示例带学习,通俗易懂,容易理解和掌握
python·算法·决策树
歪歪1006 小时前
HTML 如何转 Markdown
开发语言·chrome·python·程序人生·html
Absinthe_苦艾酒7 小时前
JVM学习专题(四)对象创建过程
java·jvm·后端
王者鳜錸7 小时前
PYTHON从入门到实践-18Django模版渲染
开发语言·python·django
hweiyu008 小时前
IDEA搭建GO环境
开发语言·后端·golang·intellij-idea·idea·intellij idea
Real_man8 小时前
RAG系统全景:架构详解与落地实践指南
后端
若梦plus8 小时前
Xata低代码服务器端数据库平台之技术分析
前端·后端
若梦plus8 小时前
Xano低代码后端开发平台之技术分析
前端·后端