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"]
}
相关推荐
只怕自己不够好14 分钟前
手写体识别Tensorflow实现
人工智能·python·tensorflow
想去看海98528 分钟前
如何在pycharm中 判断是否成功安装pytorch环境
ide·python·pycharm
世间万物皆对象31 分钟前
Spring Boot核心概念:依赖管理
java·spring boot·后端
YRr YRr33 分钟前
ubuntu20.04 解决Pycharm没有写入权限,无法通过检查更新更新的问题
ide·python·pycharm·ubuntu20.04
孤客网络科技工作室1 小时前
Python Tornado框架教程:高性能Web框架的全面解析
前端·python·tornado
我命由我123451 小时前
7.Java 注解和元注解(三种注解、四种元注解)
java·开发语言·笔记·后端·java-ee·intellij-idea·intellij idea
青石横刀策马1 小时前
Python学习笔记(2)正则表达式
笔记·python·学习
直裾1 小时前
Scala的Set集合
开发语言·后端·scala
anqi271 小时前
Scala 的Map集合
开发语言·后端·scala
1momomo汉堡包1 小时前
Scala的Array(1)
开发语言·后端·scala