Last active
February 5, 2022 15:29
-
-
Save notsobad/5771635 to your computer and use it in GitHub Desktop.
Tornado basic auth example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding= utf-8 -*- | |
import datetime | |
import os | |
import json | |
import tornado.ioloop | |
import tornado.web | |
import tornado | |
import tornado.httpclient | |
import traceback | |
import urllib2 | |
import base64 | |
import functools | |
import hashlib,base64,random | |
API_KEYS = { | |
'rjtzWc674hDxTSWulgETRqHrVVQoI3T8f9RoMlO6zsQ': 'test' | |
} | |
def api_auth(username, password): | |
if username in API_KEYS: | |
return True | |
return False | |
def basic_auth(auth): | |
def decore(f): | |
def _request_auth(handler): | |
handler.set_header('WWW-Authenticate', 'Basic realm=JSL') | |
handler.set_status(401) | |
handler.finish() | |
return False | |
@functools.wraps(f) | |
def new_f(*args): | |
handler = args[0] | |
auth_header = handler.request.headers.get('Authorization') | |
if auth_header is None: | |
return _request_auth(handler) | |
if not auth_header.startswith('Basic '): | |
return _request_auth(handler) | |
auth_decoded = base64.decodestring(auth_header[6:]) | |
username, password = auth_decoded.split(':', 2) | |
if (auth(username, password)): | |
f(*args) | |
else: | |
_request_auth(handler) | |
return new_f | |
return decore | |
class ResHandler(tornado.web.RequestHandler): | |
@basic_auth(api_auth) | |
def get(self): | |
self.write("hello") | |
app = tornado.web.Application([ | |
(r'/api/res/', ResHandler), | |
], **settings) | |
if __name__ == '__main__': | |
import tornado.options | |
tornado.options.parse_command_line() | |
app.listen(9527) | |
tornado.ioloop.IOLoop.instance().start() |
This is the appropriate client implementation:
from urllib.request import Request, urlopen
import json
import base64
#===============================================================================
def FetchData(url, user, passwd, as_json=False):
#===============================================================================
auth = dict(Authorization = b"Basic " + base64.b64encode((user+":"+passwd).encode()))
req = Request(url, headers=auth)
resp = urlopen(req).read().decode()
if as_json:
resp = json.loads(resp)
return resp
#===============================================================================
if __name__ == "__main__":
#===============================================================================
from pprint import pprint
ret = FetchData("http://localhost:8888", "test", "abcd")
pprint(ret)
(Tested with python 3.6.1)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Maybe someone will prefer the use of object oriented programming instead of using decorators:
It is sufficient to derive your own class from
BasicAuthHandler
. If you don't want use theprepare
-method, rename it and call it at the beginning of your GET or POST handler. Your following code will be executed only, if the authorization has been performed.