Skip to content

Instantly share code, notes, and snippets.

@jhass
Forked from yorkxin/README.md
Last active May 7, 2024 07:11
Show Gist options
  • Save jhass/652dd780d23c1e236ff913e8a2b77eb2 to your computer and use it in GitHub Desktop.
Save jhass/652dd780d23c1e236ff913e8a2b77eb2 to your computer and use it in GitHub Desktop.
Proxy to remote server with CORS support

cors.py for mitmproxy

Hacking CORS restriction to enable in-browser XHR to any server.

Usage

Say you are running an web app at localhost, and you want to send XHR to http://remote-server:80, but the CORS restriction forbids access because you are sending requests from an origin that remote-server:80 does not allow.

Run:

mitmproxy -s cors.py -R http://remote-server:80 -b localhost -p 8080

Now localhost:8080 is tunnelled to remote-server:80.

And you can XHR to proxied server from localhost:

fetch("http://localhost:8080/api.json")
  .then(function(response) {
    // enjoy the response
  });

Bonus: You can inspect HTTP requests in mitmproxy.

from mitmproxy import http
def response(flow):
flow.response.headers["Access-Control-Allow-Origin"] = "*"
# Use this if the application sends auth info via header
flow.response.headers["Access-Control-Expose-Headers"] = "Authorization"
def request(flow):
# Hijack CORS OPTIONS request
if flow.request.method == "OPTIONS":
flow.response = http.Response.make(200, b"",
{"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,POST",
"Access-Control-Allow-Headers": "Authorization",
"Access-Control-Max-Age": "1728000"})
@lasicmk2
Copy link

lasicmk2 commented Mar 2, 2023

hi

the syntax changed a bit lastly and to make this script working, there is a need to replace 'HTTPResponse' with 'Response'
jvilk/mitmproxy-node#13

if flow.request.method == "OPTIONS":
flow.response = http.Response.make(202, b"",
{"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,POST",
"Access-Control-Allow-Headers": "Authorization",
"Access-Control-Max-Age": "1728000"})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment