Basic HTTP/1.0 Authentication
The basic method is an implementation of basic authentication as described in
HTTP/1.0 specification .
Warning
Do not use this example in production sites unless you are using
SSL or need to work with very out-dated clients because the password entered is
transmitted in plain text, instead use Digest HTTP/1.1 Authentication.
HTTP Basic Authentication is perhaps the easiest way to add authentication to
your website. When your application returns a 401 status code the visitor's
browser will promot them for a username and password if they haven't already
signed in.
The AuthKit middleware will check the username and password and sign in the
visitor only if password was correct.
The code looks like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 | from authkit.authenticate import middleware, sample_app
def valid(environ, username, password):
return username == password
app = middleware(
sample_app,
setup_method='basic',
basic_realm='Test Realm',
basic_authenticate_function=valid
)
if __name__ == '__main__':
from paste.httpserver import serve
serve(app, host='0.0.0.0', port=8080)
|
The realm parameter is an identifier for the authority that is
requesting authorization. It is shown to the user and should be unique within
the domain it is being used. If it isn't specified, a default of AuthKit is
used.
The parameter users_valid should be a function that returns True
if the username and password are correct and False otherwise. The example
above will allow anyone with a password that is the same as their username to
sign in. In this case not entering a username or password is therefore allowed.
This isn't very secure so you should customise the function to suit
your setup.
Note
Bear in mind that in authentication systems usernames are usually
case insensitive and passwords are case sensitive. Your users will
probably expect your system to follow this general rule.
If the visitor presses Cancel they will be shown the 403 Unauthorized response.
If a user has been signed in the REMOTE_USER environment variable will be
set with their username so you can access it in your application code as
environ['REMOTE_USER'].
The example above is available in the examples/docs directory and can be
run with:
python basic.py
If you run the program you will be able to visit http://localhost:8080 but will
be prompted to sign in if you visit http://localhost:8080/private and any
username password combination where the username is the same as the password
will sign you in any you will notice the REMOTE_USER variable will be set.
Note
HTTP authentication does not easily support signing out so you will
need to close the browser to test the example again.