@@ -39,26 +39,39 @@ and check that the user input is in that list:
39
39
40
40
<p >
41
41
Often this is not possible, so an alternative is to check that the target URL does not
42
- specify an explicit host name. For example, the Django framework provides a
43
- function <code >url_has_allowed_host_and_scheme</code > that can be used to check that a
44
- URL is safe to redirect to, as shown in the following example:
42
+ specify an explicit host name. For example, you can use the <code >urlparse</code > function
43
+ from the Python standard library to parse the URL and check that the <code >netloc</code >
44
+ attribute is empty.
45
+ </p >
46
+
47
+ <p >
48
+ Note, however, that many browsers accept backslash characters (<code >\</code >) as equivalent
49
+ to forward slash characters (<code >/</code >) in URLs, but the <code >urlparse</code > function
50
+ does not. To account for this, you can first replace all backslashes with forward slashes,
51
+ as shown in the following example:
45
52
</p >
46
53
47
54
<sample src =" examples/redirect_good2.py" />
48
55
49
56
<p >
50
- Note that many browsers accept backslash characters (<code >\</code >) as equivalent to
51
- forward slash characters (<code >/</code >) in URLs, so it is important to account for this
52
- when validating the URL, for example by first replacing all backslashes with forward
53
- slashes. Django's <code >url_has_allowed_host_and_scheme</code > function
54
- does this automatically, but other libraries may not.
57
+ For Django application, you can use the function <code >url_has_allowed_host_and_scheme</code >
58
+ to check that a URL is safe to redirect to, as shown in the following example:
59
+ </p >
60
+
61
+ <sample src =" examples/redirect_good3.py" />
62
+
63
+ <p >
64
+ Note that <code >url_has_allowed_host_and_scheme</code > handles backslashes correctly, so no
65
+ additional processing is required.
55
66
</p >
56
67
57
68
</example >
58
69
59
70
<references >
60
71
<li >OWASP: <a href =" https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html" >
61
72
XSS Unvalidated Redirects and Forwards Cheat Sheet</a >.</li >
73
+ <li >Python standard library: <a href =" https://docs.python.org/3/library/urllib.parse.html" >
74
+ urllib.parse</a >.</li >
62
75
</references >
63
76
64
77
</qhelp >
0 commit comments