Django:权限验证中间件如何使用

有时候我们需要在访问页面前进行权限验证,比如有些页面是需要在登录后才能进行访问,如个人中心、我的订单等。

一.后端配置中间件

1.检验逻辑

创建一个middleware.py,在里面写上检验的逻辑

复制代码
from django.http import JsonResponse
from users.models import User

class CookieAuthMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # 检查请求是否为登录请求
        if request.path == '/login/':
            return self.get_response(request)

        mobile = request.COOKIES.get('mobile')
        if mobile:
            try:
                user = User.objects.get(mobile=mobile)
                request.user = user
            except User.DoesNotExist:
                return JsonResponse({'detail': 'Unauthorized'}, status=401)
        else:
            return JsonResponse({'detail': 'Unauthorized'}, status=401)

        response = self.get_response(request)
        return response

对登录操作则不进行检验

2.配置中间件

复制代码
MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',

    'utils.middleware.CookieAuthMiddleware',
]

实际路径跟自己项目匹配,我是把中间件的文件放在了utils文件夹里

3.运行效果

可以看到这里未登录状态访问我的订单已经返回了401

二.前端页面跳转

然后我们在页面的js里配置响应拦截,如果检测到返回响应为401,则说明用户未登录,就给他跳转到登录界面

复制代码
mounted: function(){
    axios.interceptors.response.use(
        response => {
            return response;
        },
        error => {
            if (error.response && error.response.status === 401) {
                window.location.href = 'http://127.0.0.1:8080/login.html';
            } else {
                return Promise.reject(error);
            }
        }
    );}

这时我们在未登录状态下访问就会跳转到登录界面

相关推荐
chao_7894 小时前
二分查找篇——搜索旋转排序数组【LeetCode】一次二分查找
数据结构·python·算法·leetcode·二分查找
烛阴4 小时前
Python装饰器解除:如何让被装饰的函数重获自由?
前端·python
noravinsc4 小时前
django 一个表中包括id和parentid,如何通过parentid找到全部父爷id
python·django·sqlite
ajassi20004 小时前
开源 python 应用 开发(三)python语法介绍
linux·python·开源·自动化
沉默媛5 小时前
如何安装python以及jupyter notebook
开发语言·python·jupyter
Deng9452013146 小时前
基于Python的旅游数据可视化应用
python·numpy·pandas·旅游·数据可视化技术
2401_878624796 小时前
pytorch 自动微分
人工智能·pytorch·python·机器学习
胖达不服输6 小时前
「日拱一码」021 机器学习——特征工程
人工智能·python·机器学习·特征工程
screenCui7 小时前
macOS运行python程序遇libiomp5.dylib库冲突错误解决方案
开发语言·python·macos
小眼睛羊羊7 小时前
pyinstaller打包paddleocr
python