0

For study purposes I'd like to know if there is a simple dummy example of how to handle a http request with basic authentication using python. I'd like to follow the same pattern from a example I've found and adapted, as follows:

'''webservice.py'''
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.auth
from tornado.web import HTTPError

from tornado.escape import json_encode as dumps
from tornado.escape import json_decode as loads

import db
import settings

class MainHandler(tornado.web.RequestHandler):
    """Main Handler... list all databases"""

    def get(self):
        self.write(dumps(db.list_databases()))

application = tornado.web.Application([
    (r"/", MainHandler),
],
    cookie_secret='PUT_SOME_CODE',
)

if __name__ == "__main__":
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(settings.port)
    tornado.ioloop.IOLoop.instance().start()

A list of databases appears when reach http://localhost:8888/, which is the purpose of the script. This can be accessed by browser and a tester script like:

'''tester.py'''
from tornado.httpclient import HTTPClient
from tornado.escape import json_decode as loads

url='http://localhost:8888/'

http_client=HTTPClient()
response=http_client.fetch(url)
listResponse=loads(response.body)


print(listResponse)

http_client.close()
Julio
  • 3
  • 3
  • [restful auth](http://stackoverflow.com/questions/319530/restful-authentication?rq=1) and [python restful great example](https://github.com/miguelgrinberg/api-pycon2015). – sobolevn May 18 '15 at 19:47

1 Answers1

0

Here is simplest basic-auth example. Of course, it can be improved in many ways, it is just a demonstration how it usually works.

import httplib


class MainHandler(tornado.web.RequestHandler):
    """Main Handler... list all databases"""

    def get(self):
        self.check_basic_auth()
        do_stuff()

    def check_basic_auth(self):
        if not self.test_auth_credentials():
            raise HTTPError(httplib.UNAUTHORIZED, 
                            headers={'WWW-Authenticate': 'Basic realm="Auth realm"'})

    def test_auth_credentials(self):
        auth_header = self.request.headers.get('Authorization')

        if auth_header and auth_header.startswith('Basic '):
            method, auth_b64 = auth_header.split(' ')
            try:
                decoded_value = auth_b64.decode('base64')
            except ValueError:
                return False
            given_login, _, given_passwd = decoded_value.partition(':')
            return <YOUR_LOGIN> == given_login and <YOUR_PASSWORD> == given_passwd
        return False
Alex Pertsev
  • 931
  • 4
  • 13