For more sophisticated authentication needs, HTTP Digest is a ready solution. To use it in your Flask app, start by extending the authdigest contribution to werkzeug with Flask knowledge:
from functools import wraps
from werkzeug.contrib import authdigest
import flask
class FlaskRealmDigestDB(authdigest.RealmDigestDB):
def requires_auth(self, f):
@wraps(f)
def decorated(*args, **kwargs):
request = flask.request
if not self.isAuthenticated(request):
return self.challenge()
return f(*args, **kwargs)
return decorated
The create a digest database to hold your user authentication data:
authDB = FlaskRealmDigestDB('MyAuthRealm')
authDB.add_user('admin', 'test')
Use the authDB.requires_auth instance method to wrap a view function:
from flask import request, session
@app.route('/')
@authDB.requires_auth
def auth():
session['user'] = request.authorization.username
return "<h1>Content for authenticated user</h1>"
Or use the instance of authDB directly:
@app.route('/auth')
def authApi():
if not authDB.isAuthenticated(request):
return authDB.challenge()
session['user'] = request.authorization.username
return "<h1>Content for authenticated user</h1>"
The authdigest module was brought to you by Shane Holloway, under the same license as Werkzeug and Flask.
- Updates -
2013 April: Submit pull requests or fork flask-digestauth from BitBucket.
This snippet by Shane Holloway can be used freely for anything you like. Consider it public domain.
Comments
Moved to Github by Shane Holloway on 2012-02-22 @ 15:42
I just moved the fork of werkzeug to github (https://github.com/shanewholloway/werkzeug/) from BitBucket.
requests by Peter Douma on 2013-03-23 @ 02:07
Thanks, this works great. But there is one issue. I used the requests library to test it, and if you put in the wrong password or user, in response = requests.get( 'http://localhost:8000/', auth = HTTPDigestAuth( 'admin', 'junk') )
it goes in a recursive loop.
flask-digestauth repo by Shane Holloway on 2013-04-05 @ 15:19
We just recently migrated a bunch of repositories from our private server to bitbucket. The code can be found at https://bitbucket.org/shanewholloway/flask-digestauth
@Peter by Shane Holloway on 2013-04-05 @ 15:25
Peter, feel free to fix the issue and submit a pull request to the bitbucket repo.