| 1 |
Getting Started |
| 2 |
=============== |
| 3 |
|
| 4 |
Installation |
| 5 |
------------ |
| 6 |
|
| 7 |
You can install Flask-HTTPAuth with ``pip``:: |
| 8 |
|
| 9 |
pip install flask-httpauth |
| 10 |
|
| 11 |
Basic authentication example |
| 12 |
---------------------------- |
| 13 |
|
| 14 |
The following example application uses HTTP Basic authentication to protect route ``'/'``:: |
| 15 |
|
| 16 |
from flask import Flask |
| 17 |
from flask_httpauth import HTTPBasicAuth |
| 18 |
from werkzeug.security import generate_password_hash, check_password_hash |
| 19 |
|
| 20 |
app = Flask(__name__) |
| 21 |
auth = HTTPBasicAuth() |
| 22 |
|
| 23 |
users = { |
| 24 |
"john": generate_password_hash("hello"), |
| 25 |
"susan": generate_password_hash("bye") |
| 26 |
} |
| 27 |
|
| 28 |
@auth.verify_password |
| 29 |
def verify_password(username, password): |
| 30 |
if username in users and \ |
| 31 |
check_password_hash(users.get(username), password): |
| 32 |
return username |
| 33 |
|
| 34 |
@app.route('/') |
| 35 |
@auth.login_required |
| 36 |
def index(): |
| 37 |
return "Hello, {}!".format(auth.current_user()) |
| 38 |
|
| 39 |
if __name__ == '__main__': |
| 40 |
app.run() |
| 41 |
|
| 42 |
The function decorated with the ``verify_password`` decorator receives the username and password sent by the client. If the credentials belong to a user, then the function should return the user object. If the credentials are invalid the function can return ``None`` or ``False``. The user object can then be queried from the ``current_user()`` method of the authentication instance. |
| 43 |
|
| 44 |
Digest authentication example |
| 45 |
----------------------------- |
| 46 |
|
| 47 |
The following example uses HTTP Digest authentication:: |
| 48 |
|
| 49 |
from flask import Flask |
| 50 |
from flask_httpauth import HTTPDigestAuth |
| 51 |
|
| 52 |
app = Flask(__name__) |
| 53 |
app.config['SECRET_KEY'] = 'secret key here' |
| 54 |
auth = HTTPDigestAuth() |
| 55 |
|
| 56 |
users = { |
| 57 |
"john": "hello", |
| 58 |
"susan": "bye" |
| 59 |
} |
| 60 |
|
| 61 |
@auth.get_password |
| 62 |
def get_pw(username): |
| 63 |
if username in users: |
| 64 |
return users.get(username) |
| 65 |
return None |
| 66 |
|
| 67 |
@app.route('/') |
| 68 |
@auth.login_required |
| 69 |
def index(): |
| 70 |
return "Hello, {}!".format(auth.username()) |
| 71 |
|
| 72 |
if __name__ == '__main__': |
| 73 |
app.run() |
| 74 |
|
| 75 |
Token Authentication Example |
| 76 |
---------------------------- |
| 77 |
|
| 78 |
The following example application uses a custom HTTP authentication scheme to protect route ``'/'`` with a token:: |
| 79 |
|
| 80 |
from flask import Flask |
| 81 |
from flask_httpauth import HTTPTokenAuth |
| 82 |
|
| 83 |
app = Flask(__name__) |
| 84 |
auth = HTTPTokenAuth(scheme='Bearer') |
| 85 |
|
| 86 |
tokens = { |
| 87 |
"secret-token-1": "john", |
| 88 |
"secret-token-2": "susan" |
| 89 |
} |
| 90 |
|
| 91 |
@auth.verify_token |
| 92 |
def verify_token(token): |
| 93 |
if token in tokens: |
| 94 |
return tokens[token] |
| 95 |
|
| 96 |
@app.route('/') |
| 97 |
@auth.login_required |
| 98 |
def index(): |
| 99 |
return "Hello, {}!".format(auth.current_user()) |
| 100 |
|
| 101 |
if __name__ == '__main__': |
| 102 |
app.run() |
| 103 |
|
| 104 |
The ``HTTPTokenAuth`` is a generic authentication handler that can be used with non-standard authentication schemes, with the scheme name given as an argument in the constructor. In the above example, the ``WWW-Authenticate`` header provided by the server will use ``Bearer`` as scheme:: |
| 105 |
|
| 106 |
WWW-Authenticate: Bearer realm="Authentication Required" |
| 107 |
|
| 108 |
The ``verify_token`` callback receives the authentication credentials provided by the client on the ``Authorization`` header. This can be a simple token, or can contain multiple arguments, which the function will have to parse and extract from the string. As with the ``verify_password``, the function should return the user object if the token is valid. |
| 109 |
|
| 110 |
In the examples directory you can find a complete example that uses JWS tokens. JWS tokens are similar to JWT tokens. However using JWT tokens would require an external dependency. |
| 111 |
|
| 112 |
Using Multiple Authentication Schemes |
| 113 |
------------------------------------- |
| 114 |
|
| 115 |
Applications sometimes need to support a combination of authentication |
| 116 |
methods. For example, a web application could be authenticated by |
| 117 |
sending client id and secret over basic authentication, while third |
| 118 |
party API clients use a JWS or JWT bearer token. The `MultiAuth` class allows you to protect a route with more than one authentication object. To grant access to the endpoint, one of the authentication methods must validate. |
| 119 |
|
| 120 |
In the examples directory you can find a complete example that uses basic and token authentication. |
| 121 |
|
| 122 |
User Roles |
| 123 |
---------- |
| 124 |
|
| 125 |
Flask-HTTPAuth includes a simple role-based authentication system that can optionally be added to provide an additional layer of granularity in filtering accesses to routes. To enable role support, write a function that returns the list of roles for a given user and decorate it with the ``get_user_roles`` decorator:: |
| 126 |
|
| 127 |
@auth.get_user_roles |
| 128 |
def get_user_roles(user): |
| 129 |
return user.get_roles() |
| 130 |
|
| 131 |
To restrict access to a route to users having a given role, add the ``role`` argument to the ``login_required`` decorator:: |
| 132 |
|
| 133 |
@app.route('/admin') |
| 134 |
@auth.login_required(role='admin') |
| 135 |
def admins_only(): |
| 136 |
return "Hello {}, you are an admin!".format(auth.current_user()) |
| 137 |
|
| 138 |
The ``role`` argument can take a list of roles, in which case users who have any of the given roles will be granted access:: |
| 139 |
|
| 140 |
@app.route('/admin') |
| 141 |
@auth.login_required(role=['admin', 'moderator']) |
| 142 |
def admins_only(): |
| 143 |
return "Hello {}, you are an admin or a moderator!".format(auth.current_user()) |
| 144 |
|
| 145 |
In the most advanced usage, users can be filtered by having multiple roles:: |
| 146 |
|
| 147 |
@app.route('/admin') |
| 148 |
@auth.login_required(role=['user', ['moderator', 'contributor']]) |
| 149 |
def admins_only(): |
| 150 |
return "Hello {}, you are a user or a moderator/contributor!".format(auth.current_user()) |
| 151 |
|
| 152 |
Deployment Considerations |
| 153 |
------------------------- |
| 154 |
|
| 155 |
Be aware that some web servers do not pass the ``Authorization`` headers to the WSGI application by default. For example, if you use Apache with mod_wsgi, you have to set option ``WSGIPassAuthorization On`` as `documented here <https://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIPassAuthorization/>`_. |
| 156 |
|
| 157 |
Deprecated Basic Authentication Options |
| 158 |
--------------------------------------- |
| 159 |
|
| 160 |
Before the ``verify_password`` described above existed there were other simpler mechanisms for implementing basic authentication. While these are deprecated they are still maintained. However, the ``verify_password`` callback should be preferred as it provides greater security and flexibility. |
| 161 |
|
| 162 |
The ``get_password`` callback needs to return the password associated with the username given as argument. Flask-HTTPAuth will allow access only if ``get_password(username) == password``. Example:: |
| 163 |
|
| 164 |
@auth.get_password |
| 165 |
def get_password(username): |
| 166 |
return get_password_for_username(username) |
| 167 |
|
| 168 |
Using this callback alone is in general not a good idea because it requires passwords to be available in plaintext in the server. In the more likely scenario that the passwords are stored hashed in a user database, then an additional callback is needed to define how to hash a password:: |
| 169 |
|
| 170 |
@auth.hash_password |
| 171 |
def hash_pw(password): |
| 172 |
return hash_password(password) |
| 173 |
|
| 174 |
In this example, you have to replace ``hash_password()`` with the specific hashing function used in your application. When the ``hash_password`` callback is provided, access will be granted when ``get_password(username) == hash_password(password)``. |
| 175 |
|
| 176 |
If the hashing algorithm requires the username to be known then the callback can take two arguments instead of one:: |
| 177 |
|
| 178 |
@auth.hash_password |
| 179 |
def hash_pw(username, password): |
| 180 |
salt = get_salt(username) |
| 181 |
return hash_password(password, salt) |