Skip to content

Instantly share code, notes, and snippets.

Forked from yorkxin/
Last active Jun 21, 2020
What would you like to do?
Proxy to remote server with CORS support for mitmproxy

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


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.


mitmproxy -s -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:

  .then(function(response) {
    // enjoy the response

Bonus: You can inspect HTTP requests in mitmproxy.

from libmproxy.protocol.http import HTTPResponse
from netlib.http import Headers
def response(context, 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"] = "X-Application-Session-Id"
def request(context, flow):
# Hijack CORS OPTIONS request
if flow.request.method == "OPTIONS":
headers = Headers([
[b"Access-Control-Allow-Origin", b"*"],
[b"Access-Control-Allow-Methods", b"POST"],
[b"Access-Control-Allow-Headers", b"X-Application-Session-Id"],
[b"Access-Control-Max-Age", b"1728000"]
resp = HTTPResponse(b"HTTP/1.1", 200, "OK", headers, "")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment