Enable access control on simple HTTP server
access-control-allow-origin python flask
python http server authentication
python https server
python threaded http server
I have the following shell script for a very simple HTTP server:
#!/bin/sh echo "Serving at http://localhost:3000" python -m SimpleHTTPServer 3000
I was wondering how I can enable or add a CORS header like
Access-Control-Allow-Origin: * to this server?
Unfortunately, the simple HTTP server is really that simple that it does not allow any customization, especially not for the headers it sends. You can however create a simple HTTP server yourself, using most of
SimpleHTTPRequestHandler, and just add that desired header.
For that, simply create a file
simple-cors-http-server.py (or whatever) and, depending on the Python version you are using, put one of the following codes inside.
Then you can do
python simple-cors-http-server.py and it will launch your modified server which will set the CORS header for every response.
With the shebang at the top, make the file executable and put it into your PATH, and you can just run it using
Python 3 solution
#!/usr/bin/env python3 from http.server import HTTPServer, SimpleHTTPRequestHandler, test import sys class CORSRequestHandler (SimpleHTTPRequestHandler): def end_headers (self): self.send_header('Access-Control-Allow-Origin', '*') SimpleHTTPRequestHandler.end_headers(self) if __name__ == '__main__': test(CORSRequestHandler, HTTPServer, port=int(sys.argv) if len(sys.argv) > 1 else 8000)
Python 2 solution
#!/usr/bin/env python2 from SimpleHTTPServer import SimpleHTTPRequestHandler import BaseHTTPServer class CORSRequestHandler (SimpleHTTPRequestHandler): def end_headers (self): self.send_header('Access-Control-Allow-Origin', '*') SimpleHTTPRequestHandler.end_headers(self) if __name__ == '__main__': BaseHTTPServer.test(CORSRequestHandler, BaseHTTPServer.HTTPServer)
Python 2 & 3 solution
If you need compatibility for both Python 3 and Python 2, you could use this polyglot script that works in both versions. It first tries to import from the Python 3 locations, and otherwise falls back to Python 2:
#!/usr/bin/env python try: # Python 3 from http.server import HTTPServer, SimpleHTTPRequestHandler, test as test_orig import sys def test (*args): test_orig(*args, port=int(sys.argv) if len(sys.argv) > 1 else 8000) except ImportError: # Python 2 from BaseHTTPServer import HTTPServer, test from SimpleHTTPServer import SimpleHTTPRequestHandler class CORSRequestHandler (SimpleHTTPRequestHandler): def end_headers (self): self.send_header('Access-Control-Allow-Origin', '*') SimpleHTTPRequestHandler.end_headers(self) if __name__ == '__main__': test(CORSRequestHandler, HTTPServer)
Python SimpleHTTPServer Recipe: Enable CORS, This server behaves exactly the same as SimpleHTTPServer, except we send the extra header. Access-Control-Allow-Origin: *. to allow any Then you can do python simple-cors-http-server.py and it will launch your modified server which will set the CORS header for every response. With the shebang at the top, make the file executable and put it into your PATH, and you can just run it using simple-cors-http-server.py too.
Allow CORS with python simple http server · GitHub, import SimpleHTTPServer. class CORSHTTPRequestHandler(SimpleHTTPServer. No 'Access-Control-Allow-Origin' header is present on the requested Enabling HTTPS on your servers is a critical step in providing security for your web pages. Use Mozilla's Server Configuration tool to set up your server for HTTPS support. Regularly test your site
I had the same problem and came to this solution:
class Handler(SimpleHTTPRequestHandler): def send_response(self, *args, **kwargs): SimpleHTTPRequestHandler.send_response(self, *args, **kwargs) self.send_header('Access-Control-Allow-Origin', '*')
I simply created a new class inheriting from SimpleHTTPRequestHandler that only changes the
Python SimpleHTTPServer with CORS · GitHub, #!/usr/bin/env python. # Usage: python cors_http_server.py <port>. try: # try to use Python 3. from http.server import HTTPServer, SimpleHTTPRequestHandler, I was wondering how I can enable or add a CORS header like Access-Control-Allow-Origin: * to this server? Try an alternative like http-server As SimpleHTTPServer is not really the kind of server you deploy to production, I'm assuming here that you don't care that much about which tool you use as long as it does the job of exposing your files at
You'll need to provide your own instances of do_GET() (and do_HEAD() if choose to support HEAD operations). something like this:
class MyHTTPServer(SimpleHTTPServer): allowed_hosts = (('127.0.0.1', 80),) def do_GET(self): if self.client_address not in allowed_hosts: self.send_response(401, 'request not allowed') else: super(MyHTTPServer, self).do_Get()
Default value for Access-Control-Allow-Methods, How do I set access control allow origin in Python? Enable CORS in Apache. Set Access-Control-Allow-Origin (CORS) authorization to the header in Apache web server. Add the following line inside either the <Directory>, <Location>, <Files> sections under <VirtualHost> in Apache configuration files. You can also place this inside the .htaccess file. Header set Access-Control-Allow-Origin "*" Example
Simple Local CORS test tool - Pareture, It is also not possible to specify more than one Access-Control-Allow-Origin header.) At the HTTP Server level HTTP provides a general framework for access control and authentication. The most common HTTP authentication is based on the "Basic" schema. This page shows an introduction to the HTTP framework for authentication and shows how to restrict access to your server using the HTTP "Basic" schema.
CORS Enabled, Those are called “simple requests” in this article, though In response, the server sends back an Access-Control-Allow-Origin header. Access-Control-Allow-Origin: https://foo.example. So for example, instead of blocking only one host in the engineering team, you can deny access to the entire network and only allow one. Or you can also restrict the access to host C. If the Engineer from host C, needs to access a web server located in the Financial network, you can only allow port 80, and block everything else.
Cross-Origin Resource Sharing (CORS), Here's an example of what an Access-Control-Allow-Headers header might X-Custom-Header is supported by CORS requests to the server. To configure HTTP session over CORS is easy since the HTTP session are dependent on cookies. So we need to follow the two steps to enable the HTTP cookies in response to CORS. 1: First set the credentials: true in the express middleware function. It will add and Access-Control-Allow-Credentials header.
- I followed the instructions but by executing python simple-cors-http-server.py I get error: python: can't open file 'simple-cors-http-server.py': [Errno 2] No such file or directory logout....any thoughts?
- @poke The server responds with 501 Unsupported method ('OPTIONS'). I'm running OS X 10.10.1 with Python 2.7.6. Any suggestions?
HTTP/1.0 501 Unsupported method ('OPTIONS') Server: SimpleHTTP/0.6 Python/2.7.6 Date: Wed, 21 Jan 2015 23:16:10 GMT Content-Type: text/html Connection: close Access-Control-Allow-Origin: *
- @HairOfTheDog The SimpleHTTPRequestHandler doesn’t support the OPTIONS HTTP method. You could add it if you want (read the Python manual about HTTP servers); or you could just not try to access the server like that.
- @RobertoFranceschini You might be running into preflighted requests which require the
OPTIONSmethod to be implemented properly. As for simple requests, the solution of sending just the
Access-Control-Allow-Originheader should still work fine.
- @Tyguy7 That might be a general behavior with the simple HTTP server though. I had varying results regarding performance before. But for simply running a server for a moment, I still consider it the quickest solution.
- it does work fine for all my team. explain your problem please
- I'm a simple man. I see a solution that requires installing
npmon a machine that is only known to have
python, I downvote.
- @ParthianShot: you might want to learn to use the best tool for the job.
- @ParthianShot Many developers already have node/npm installed.and the question title is generic enough to drive a large audience of users that clearly don't care about python or SimpleHTTPServer, which is confirmed by upvotes. It's not because it's not helpful to you that it is for everybody. There are good reasons to not like both Node and Python as well. Things like leftpad/bad publish/bad git usage seems totally unrelated to me.
- Adding an additional language and framework incurs technical debt and increases the attack surface of an environment. "Fatal mistakes can be made in any programming language" True, but JS makes that way easier than most other languages. And every language has gotchas; the fewer languages you use, the less likely it is that some developer who is unfamiliar with one of the languages makes a mistake that wouldn't be a mistake in another language.
- Thanks for your answer, but I have no Python knowledge what so ever, I am just using the shell script mentioned above as a simple http server for my Emberjs apps. Only when collided with the access control problem, I researched to find that I need to enable it in this simple http server. So after some research I added (enable 'CrossOrigin', origins => '*';) but not-surprisingly it didn't work. If you can please point me to any Python simple http server shell script that include the access control feature that will be highly appreciated
- On a minor note, I am not trying to be lazy here really but start learning python just to add this feature to the simpleHTTP server doesn't sound logical at this point so I was hoping it will be easy to add OR hopefully I can find an alternative / ready made Python script that can do the job so that I can continue with my dev work
- The SimpleHTTPServer has no options to support access controls. Either you'll need to roll your own code -- or switch to another web server that supports access controls. Think about lighttpd.net