1.认证
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):
jwt_token = request.query_params.get("token")
if not jwt_token:
return AuthenticationFailed("认证失败")
try:
verified_payload = jwt.decode(jwt_token, settings.SECRET_KEY, algorithms="HS256")
print(verified_payload)
except Exception as e:
raise AuthenticationFailed("认证失败")
user = User(**verified_payload)
return user, jwt
def authenticate_header(self, request):
return "API"
2.权限
from rest_framework.permissions import BasePermission
from rbac import settings
class RbacPermission(BasePermission):
def has_permission(self, request, view):
user_role = request.user.role
user_total_permission = settings.PERMISSION.get(user_role)
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.全局配置
REST_FRAMEWORK = {
"UNAUTHENTICATED_USER": None,
"UNAUTHENTICATED_TOKEN": None,
"DEFAULT_AUTHENTICATION_CLASSES": ["utils.auth.RbacAuthentication"],
"DEFAULT_PERMISSION_CLASSES": ["utils.permission.RbacPermission"]
}