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"]
}
相关推荐
why1513 小时前
微服务商城-商品微服务
数据库·后端·golang
山海不说话4 小时前
视频行为标注工具BehaviLabel(源码+使用介绍+Windows.Exe版本)
人工智能·python·计算机视觉·视觉检测
liuzhenghua666 小时前
Python任务调度模型
java·运维·python
結城6 小时前
mybatisX的使用,简化springboot的开发,不用再写entity、mapper以及service了!
java·spring boot·后端
小前端大牛马6 小时前
java教程笔记(十一)-泛型
java·笔记·python
sjtu_cjs6 小时前
Tensorrt python api 10.11.0笔记
开发语言·笔记·python
哆啦A梦的口袋呀6 小时前
深入理解系统:UML类图
开发语言·python·uml
虎冯河6 小时前
怎么让Comfyui导出的图像不包含工作流信息,
开发语言·python
星辰离彬6 小时前
Java 与 MySQL 性能优化:MySQL 慢 SQL 诊断与分析方法详解
java·spring boot·后端·sql·mysql·性能优化
q_19132846956 小时前
基于Springboot+Vue的办公管理系统
java·vue.js·spring boot·后端·intellij idea