简体   繁体   English

使用协议“帐户”不安全重定向到 URL

[英]Unsafe redirect to URL with protocol 'account'

I am trying to redirect to login page with return url through a middleware.我正在尝试通过中间件返回 url 重定向到登录页面。

I am getting this error so can anyone answer the question why i am getting this error and how to solve this error我收到此错误,因此任何人都可以回答为什么我收到此错误以及如何解决此错误的问题

from django.shortcuts import redirect
def auth_middleware(get_response):
     def middleware(request):
        print("Middleware")
        return_url = request.META['PATH_INFO']
        if not request.session.get('user_id'):
            return redirect(f'account:login?return_url={return_url}')
        response = get_response(request)
        return response

    return middleware

Django will make a redirect to account:login?return_url=some_url , but the browser does not understand this: since it sees a URL that starts with account: , it assumes that account: is the protocol. Django 将重定向到account:login?return_url=some_url ,但浏览器不理解这一点:因为它看到一个 URL 以account:开头,它假设account:是协议。

We can reverse the view withreverse(…) [Django-doc] :我们可以使用reverse(…) [Django-doc]反转视图:

from django.urls import reverse
from django.http import HttpResponseRedirect

def auth_middleware(get_response):
     def middleware(request):
        print("Middleware")
        return_url = request.META['PATH_INFO']
        if not request.session.get('user_id'):
            return HttpResponseRedirect(f'{reverse("account:login")}?return_url={return_url}')
        response = get_response(request)
        return response

    return middleware

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM