I am developing a simple web application written in Flask to understand browser authentication from scratch. As a first step, I added Basic Authentication just to stop anonymous access using:
from functools import wraps
from flask import request, Response
def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
"""
return username == 'admin' and password == 'secret'
def authenticate():
"""Sends a 401 response that enables basic auth"""
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
Source: http://flask.pocoo.org/snippets/8/
It works fine as far as security is concerned. But the problem is that it prompts me for a username and password. Once I give the username and password, the authorization is persistent. So my question is:
1) How is that the authorization is persistent? Is the Basic Authorization stored in the request header throughout the browser session? I can see that when I open an incognito window I again need to type it just once.
2) To make it more user friendly, can I have a login page that does the above job i.e set a persistent Basic Authorization throught the browser session using pure Javscript instaed of doing it using a browser popup?