Skip to content

Instantly share code, notes, and snippets.

@tokibito
Created May 25, 2011 01:00
Show Gist options
  • Save tokibito/990110 to your computer and use it in GitHub Desktop.
Save tokibito/990110 to your computer and use it in GitHub Desktop.
basic auth middleware
AUTH_RESPONSE_BODY = """<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html lang="ja">
<head>
<title>401 Authorization Required</title>
</head>
<body>401 Authorization Required</body>
</html>"""
def auth_required_app(environ, start_response, relm):
start_response('401 Authorization Required', [
('WWW-Authenticate', 'Basic realm="%s"' % relm),
('Content-Type', 'text/html; charset=iso-8859-1'),
])
return AUTH_RESPONSE_BODY
class AuthMiddleware(object):
def __init__(self, application, relm, username, password):
self.application = application
self.relm = relm
self.username = username
self.password = password
def get_token(self):
import base64
return base64.b64encode('%s:%s' % (self.username, self.password))
def get_auth_basic_header(self):
return 'Basic %s' % self.get_token()
def __call__(self, environ, start_response):
auth_header = environ.get('HTTP_AUTHORIZATION')
if auth_header and auth_header == self.get_auth_basic_header():
return self.application(environ, start_response)
return auth_required_app(environ, start_response, self.relm)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment