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"]
}
相关推荐
孙胜完不了31 分钟前
Day29
python
lkx0978832 分钟前
第四天的尝试
python
lcccyyy11 小时前
day 29
python
(・Д・)ノ2 小时前
python打卡day29
开发语言·python
有杨既安然2 小时前
Python高级特性深度解析:从熟练到精通的跃迁之路
开发语言·python·数据挖掘·flask
蹦蹦跳跳真可爱5892 小时前
Python----神经网络(《Searching for MobileNetV3》论文概括和MobileNetV3网络)
人工智能·python·深度学习·神经网络
妄想成为master2 小时前
如何完美安装GPU版本的torch、torchvision----解决torch安装慢 无法安装 需要翻墙安装 安装的是GPU版本但无法使用的GPU的错误
人工智能·pytorch·python·环境配置
wanfeng_093 小时前
CMS(plone / joomla 搭建测试)
python·多站点·本地搭建·joomla·plone
浩皓素3 小时前
Python函数库调用实战:以数据分析为例
python
不再幻想,脚踏实地3 小时前
Spring AOP从0到1
java·后端·spring