If you try to redirect to something other than http [s] or ftp using HttpResponseRedirect, a SuspiciousOperation exception will occur as shown below.
SuspiciousOperation: Unsafe redirect to URL with protocol 'com.example.app.sample0'
You can work around this exception by adding code like the following: Just add a redirect to allowed_schemes that you don't want to raise an exception.
try:
from django.http.response import HttpResponseRedirectBase
HttpResponseRedirectBase.allowed_schemes += ['com.example.app.sample0', ]
except ImportError:
pass
Regarding import, in the old version, django.http and below were not divided into reponse and request. So when the version of Django is old (about 1.4 series or earlier, I forgot the detailed version), import is the following code.
from django.http import HttpResponseRedirectBase
If it is within the range of Web pages that are normally viewed with a browser, it is unlikely that you want to skip to a redirect destination other than http [s] and ftp. For example, when targeting a smartphone app, you want to redirect to'[app package name]: //' (example: when returning control from the authentication URL to the app with OAuth), and so on.
This exception on redirects was introduced in the Django 1.4 series.
The actual code of HttpResponseRedirectBase is as follows, and it is easy to see that the redirect destination should be added to allowed_schemes. Since the code was introduced as a security measure, it is better to limit the redirect destination as much as possible as in the sample above.
response.py
class HttpResponseRedirectBase(HttpResponse):
allowed_schemes = ['http', 'https', 'ftp']
def __init__(self, redirect_to, *args, **kwargs):
parsed = urlparse(redirect_to)
if parsed.scheme and parsed.scheme not in self.allowed_schemes:
raise SuspiciousOperation("Unsafe redirect to URL with protocol '%s'" % parsed.scheme)
super(HttpResponseRedirectBase, self).__init__(*args, **kwargs)
self['Location'] = iri_to_uri(redirect_to)
url = property(lambda self: self['Location'])
Recommended Posts