Skip to content
Find file
Fetching contributors…
Cannot retrieve contributors at this time
68 lines (56 sloc) 1.92 KB
layout title
Basic authentication

Basic authentication


This is a proof of concept implementation of doing basic authentication with You may want to read RFC 2617 or for reference.


Create a python file containing the code below and start the script. When you enter the url http://localhost:8080/ you will be redirected to the url http://localhost:8080/login. When you are successfully authenticated, you will be redirected to the index page.

import web
import re
import base64

urls = (

app = web.application(urls,globals())

allowed = (

class Index:
    def GET(self):
        if web.ctx.env.get('HTTP_AUTHORIZATION') is not None:
            return 'This is the index page'
            raise web.seeother('/login')

class Login:
    def GET(self):
        auth = web.ctx.env.get('HTTP_AUTHORIZATION')
        authreq = False
        if auth is None:
            authreq = True
            auth = re.sub('^Basic ','',auth)
            username,password = base64.decodestring(auth).split(':')
            if (username,password) in allowed:
                raise web.seeother('/')
                authreq = True
        if authreq:
            web.header('WWW-Authenticate','Basic realm="Auth example"')
            web.ctx.status = '401 Unauthorized'

if __name__=='__main__':


Do not use this code on real site - this is only for illustration.

Something went wrong with that request. Please try again.