2013-11-28T07:33:19Z

RESTful Authentication with Flask

This article is the fourth in my series on RESTful APIs. Today I will be showing you a simple, yet secure way to protect a Flask based API with password or token based authentication.

This article stands on its own, but if you feel you need to catch up here are the links to the previous articles:

Example Code

The code discussed in the following sections is available for you to try and hack. You can find it on GitHub: REST-auth. Note that the GitHub repository likely has code that is newer than what I'm going to show in this article. If you want to see the version of the code featured in this article use this link.

The User Database

To give this example some resemblance to a real life project I'm going to use a Flask-SQLAlchemy database to store users.

The user model will be very simple. For each user a username and a password_hash will be stored.

class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key = True)
    username = db.Column(db.String(32), index = True)
    password_hash = db.Column(db.String(128))

For security reasons the original password will not be stored, after the hash is calculated during registration it will be discarded. If this user database were to fall in malicious hands it would be extremely hard for the attacker to decode the real passwords from the hashes.

Passwords should never be stored in the clear in a user database.

Password Hashing

To create the password hashes I'm going to use PassLib, a package dedicated to password hashing.

PassLib provides several hashing algorithms to choose from. The custom_app_context object is an easy to use option based on the sha256_crypt hashing algorithm.

To add password hashing and verification two new methods are added to the User model:

from passlib.apps import custom_app_context as pwd_context

class User(db.Model):
    # ...

    def hash_password(self, password):
        self.password_hash = pwd_context.encrypt(password)

    def verify_password(self, password):
        return pwd_context.verify(password, self.password_hash)

The hash_password() method takes a plain password as argument and stores a hash of it with the user. This method is called when a new user is registering with the server, or when the user changes the password.

The verify_password() method takes a plain password as argument and returns True if the password is correct or False if not. This method is called whenever the user provides credentials and they need to be validated.

You may ask how can the password be verified if the original password was thrown away and lost forever after it was hashed.

Hashing algorithms are one-way functions, meaning that they can be used to generate a hash from a password, but they cannot be used in the reverse direction. But these algorithms are deterministic, given the same inputs they will always generate the same output. All PassLib needs to do to verify a password is to hash it with the same function that was used during registration, and then compare the resulting hash against the one stored in the database.

User Registration

In this example, a client can register a new user with a POST request to /api/users. The body of the request needs to be a JSON object that has username and password fields.

The implementation of the Flask route is shown below:

@app.route('/api/users', methods = ['POST'])
def new_user():
    username = request.json.get('username')
    password = request.json.get('password')
    if username is None or password is None:
        abort(400) # missing arguments
    if User.query.filter_by(username = username).first() is not None:
        abort(400) # existing user
    user = User(username = username)
    user.hash_password(password)
    db.session.add(user)
    db.session.commit()
    return jsonify({ 'username': user.username }), 201, {'Location': url_for('get_user', id = user.id, _external = True)}

This function is extremely simple. The username and password arguments are obtained from the JSON input coming with the request and then validated.

If the arguments are valid then a new User instance is created. The username is assigned to it, and the password is hashed using the hash_password() method. The user is finally written to the database.

The body of the response shows the user representation as a JSON object, with a status code of 201 and a Location header pointing to the URI of the newly created user.

Note: the implementation of the get_user endpoint is now shown here, you can find it in the full example on github.

Here is an example user registration request sent from curl:

$ curl -i -X POST -H "Content-Type: application/json" -d '{"username":"miguel","password":"python"}' http://127.0.0.1:5000/api/users
HTTP/1.0 201 CREATED
Content-Type: application/json
Content-Length: 27
Location: http://127.0.0.1:5000/api/users/1
Server: Werkzeug/0.9.4 Python/2.7.3
Date: Thu, 28 Nov 2013 19:56:39 GMT

{
  "username": "miguel"
}

Note that in a real application this would be done over secure HTTP. There is no point in going through the effort of protecting the API if the login credentials are going to travel through the network in clear text.

Password Based Authentication

Now let's assume there is a resource exposed by this API that needs to be available only to registered users. This resource is accessed at the /api/resource endpoint.

To protect this resource I'm going to use HTTP Basic Authentication, but instead of implementing this protocol by hand I'm going to let the Flask-HTTPAuth extension do it for me.

Using Flask-HTTPAuth an endpoint is protected by adding the login_required decorator to it:

from flask_httpauth import HTTPBasicAuth
auth = HTTPBasicAuth()

@app.route('/api/resource')
@auth.login_required
def get_resource():
    return jsonify({ 'data': 'Hello, %s!' % g.user.username })

But of course Flask-HTTPAuth needs to be given some more information to know how to validate user credentials, and for this there are several options depending on the level of security implemented by the application.

The option that gives the maximum flexibility (and the only that can accomodate PassLib hashes) is implemented through the verify_password callback, which is given the username and password and is supposed to return True if the combination is valid or False if not. Flask-HTTPAuth invokes this callback function whenever it needs to validate a username and password pair.

An implementation of the verify_password callback for the example API is shown below:

@auth.verify_password
def verify_password(username, password):
    user = User.query.filter_by(username = username).first()
    if not user or not user.verify_password(password):
        return False
    g.user = user
    return True

This function finds the user by the username, then verifies the password using the verify_password() method. If the credentials are valid then the user is stored in Flask's g object so that the view function can use it.

Here is an example curl request that gets the protected resource for the user registered above:

$ curl -u miguel:python -i -X GET http://127.0.0.1:5000/api/resource
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 30
Server: Werkzeug/0.9.4 Python/2.7.3
Date: Thu, 28 Nov 2013 20:02:25 GMT

{
  "data": "Hello, miguel!"
}

If an incorrect login is used, then this is what happens:

$ curl -u miguel:ruby -i -X GET http://127.0.0.1:5000/api/resource
HTTP/1.0 401 UNAUTHORIZED
Content-Type: text/html; charset=utf-8
Content-Length: 19
WWW-Authenticate: Basic realm="Authentication Required"
Server: Werkzeug/0.9.4 Python/2.7.3
Date: Thu, 28 Nov 2013 20:03:18 GMT

Unauthorized Access

Once again I feel the need to reiterate that in a real application the API should be available on secure HTTP only.

Token Based Authentication

Having to send the username and the password with every request is inconvenient and can be seen as a security risk even if the transport is secure HTTP, since the client application must have those credentials stored without encryption to be able to send them with the requests.

An improvement over the previous solution is to use a token to authenticate requests.

The idea is that the client application exchanges authentication credentials for an authentication token, and in subsequent requests just sends this token.

Tokens are usually given out with an expiration time, after which they become invalid and a new token needs to be obtained. The potential damage that can be caused if a token is leaked is much smaller due to their short life span.

There are many ways to implement tokens. A straightforward implementation is to generate a random sequence of characters of certain length that is stored with the user and the password in the database, possibly with an expiration date as well. The token then becomes sort of a plain text password, in that can be easily verified with a string comparison, plus a check of its expiration date.

A more elaborated implementation that requires no server side storage is to use a cryptographically signed message as a token. This has the advantage that the information related to the token, namely the user for which the token was generated, is encoded in the token itself and protected against tampering with a strong cryptographic signature.

Flask uses a similar approach to write secure cookies. This implementation is based on a package called itsdangerous, which I will also use here.

The token generation and verification can be implemented as additional methods in the User model:

from itsdangerous import (TimedJSONWebSignatureSerializer
                          as Serializer, BadSignature, SignatureExpired)

class User(db.Model):
    # ...

    def generate_auth_token(self, expiration = 600):
        s = Serializer(app.config['SECRET_KEY'], expires_in = expiration)
        return s.dumps({ 'id': self.id })

    @staticmethod
    def verify_auth_token(token):
        s = Serializer(app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except SignatureExpired:
            return None # valid token, but expired
        except BadSignature:
            return None # invalid token
        user = User.query.get(data['id'])
        return user

In the generate_auth_token() method the token is an encrypted version of a dictionary that has the id of the user. The token will also have an expiration time embedded in it, which by default will be of ten minutes (600 seconds).

The verification is implemented in a verify_auth_token() static method. A static method is used because the user will only be known once the token is decoded. If the token can be decoded then the id encoded in it is used to load the user, and that user is returned.

The API needs a new endpoint that the client can use to request a token:

@app.route('/api/token')
@auth.login_required
def get_auth_token():
    token = g.user.generate_auth_token()
    return jsonify({ 'token': token.decode('ascii') })

Note that this endpoint is protected with the auth.login_required decorator from Flask-HTTPAuth, which requires that username and password are provided.

What remains is to decide how the client is to include this token in a request.

The HTTP Basic Authentication protocol does not specifically require that usernames and passwords are used for authentication, these two fields in the HTTP header can be used to transport any kind of authentication information. For token based authentication the token can be sent as a username, and the password field can be ignored.

This means that now the server can get some requests authenticated with username and password, while others authenticated with an authentication token. The verify_password callback needs to support both authentication styles:

@auth.verify_password
def verify_password(username_or_token, password):
    # first try to authenticate by token
    user = User.verify_auth_token(username_or_token)
    if not user:
        # try to authenticate with username/password
        user = User.query.filter_by(username = username_or_token).first()
        if not user or not user.verify_password(password):
            return False
    g.user = user
    return True

This new version of the verify_password callback attempts authentication twice. First it tries to use the username argument as a token. If that doesn't work, then username and password are verified as before.

The following curl request gets an authentication token:

$ curl -u miguel:python -i -X GET http://127.0.0.1:5000/api/token
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 139
Server: Werkzeug/0.9.4 Python/2.7.3
Date: Thu, 28 Nov 2013 20:04:15 GMT

{
  "token": "eyJhbGciOiJIUzI1NiIsImV4cCI6MTM4NTY2OTY1NSwiaWF0IjoxMzg1NjY5MDU1fQ.eyJpZCI6MX0.XbOEFJkhjHJ5uRINh2JA1BPzXjSohKYDRT472wGOvjc"
}

Now the protected resource can be obtained authenticating with the token:

$ curl -u eyJhbGciOiJIUzI1NiIsImV4cCI6MTM4NTY2OTY1NSwiaWF0IjoxMzg1NjY5MDU1fQ.eyJpZCI6MX0.XbOEFJkhjHJ5uRINh2JA1BPzXjSohKYDRT472wGOvjc:unused -i -X GET http://127.0.0.1:5000/api/resource
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 30
Server: Werkzeug/0.9.4 Python/2.7.3
Date: Thu, 28 Nov 2013 20:05:08 GMT

{
  "data": "Hello, miguel!"
}

Note that in this last request the password is written as the word unused. The password in this request can be anything, since it isn't used.

OAuth Authentication

When talking about RESTful authentication the OAuth protocol is usually mentioned.

So what is OAuth?

OAuth can be many things. It is most commonly used to allow an application (the consumer) to access data or services that the user (the resource owner) has with another service (the provider), and this is done in a way that prevents the consumer from knowing the login credentials that the user has with the provider.

For example, consider a website or application that asks you for permission to access your Facebook account and post something to your timeline. In this example you are the resource holder (you own your Facebook timeline), the third party application is the consumer and Facebook is the provider. Even if you grant access and the consumer application writes to your timeline, it never sees your Facebook login information.

This usage of OAuth does not apply to a client/server RESTful API. Something like this would only make sense if your RESTful API can be accessed by third party applications (consumers).

In the case of a direct client/server communication there is no need to hide login credentials, the client (curl in the examples above) receives the credentials from the user and uses them to authenticate requests with the server directly.

OAuth can do this as well, and then it becomes a more elaborated version of the example described in this article. This is commonly referred to as the "two-legged OAuth", to contrast it to the more common "three-legged OAuth".

If you decide to support OAuth there are a few implementations available for Python listed in the OAuth website.

Conclusion

I hope this article helped you understand how to implement user authentication for your API.

Once again, you can download and play with a fully working implementation of the server described above. You can find the software on my GitHub site: REST-auth. Once again keep in mind that from time to time I update the code on GitHub. Use this link to access the code version featured in this article.

If you have any questions or found any flaws in the solution I presented please let me know below in the comments.

Miguel

205 comments

  • #26 Miguel Grinberg said 2014-02-19T06:35:49Z

    @zimyand: Yes, in fact in the book I have modified this example to not accept a token as authentication when asking for another token. The way I did it is by writing a variable in flask.g that indicates if authentication was done with token or with username/password, so that the get_token() view function can determine if it can proceed or not.

  • #27 Scott said 2014-02-23T21:23:25Z

    Great tutorial! This has been incredibly helpful. I did however find an error in the User model when using MySQL. The column for password_hash needs to be at least 120 characters to properly store a SHA512 hash.

    QUICK FIX: from: password_hash = db.Column(db.String(64)) to: password_hash = db.Column(db.String(120) and reload the db to ensure the table change takes effect.

    Details: Using Mysql, PassLib raised "ValueError" for a malformed SHA512 hash. Problem is the User model didn't make enough space to save all of the hash in column "password_hash".

    relevant traceback output:

    FILE: ./flask/lib/python2.7/site-packages/passlib/utils/handlers.py", line 443, in _norm_checksum raise exc.ChecksumSizeError(self, raw=raw) ValueError: malformed sha512_crypt hash (checksum must be exactly 86 chars)

    How to fix:

    Alter the password_hash column to accomodate at least 120 characters (for an 86 char hash + additional metadata the SHA512 algorithm stores)

  • #28 Miguel Grinberg said 2014-02-24T00:37:10Z

    @Scott: thanks, you are correct. On 64-bit systems SHA512 is used. I sized the hash based on SHA256.

  • #29 Nathan Black said 2014-02-27T07:40:26Z

    In your first @auth.verify_password example:

    @auth.verify_password def verify_password(username, password): user = User.query.filter_by(username = username_or_token).first() if not user or not user.verify_password(password): return False g.user = user return True

    The query.filter_by() should filter by 'username = username' instead of 'username = username_or_token'

  • #30 Miguel Grinberg said 2014-02-27T08:01:20Z

    @Nathan: Fixed. Thanks!

  • #31 David Wood said 2014-03-25T10:18:47Z

    Great article, does Flask-HTTPAuth support Python 3+?

  • #32 Miguel Grinberg said 2014-03-26T16:41:05Z

    @David: Yes, you can use it with 2.7 and 3.3+.

  • #33 ahmedshabib said 2014-04-02T16:11:51Z

    How do you invalidate a token for a user.

  • #34 Miguel Grinberg said 2014-04-02T16:17:23Z

    @ahmedshabib: to be able to invalidate tokens you have to use a different token validation algorithm. You can generate random tokens, store them in the database under each user and validate them checking the database. Then to invalidate the token you just delete it from the database.

  • #35 Jonathan said 2014-06-05T05:45:31Z

    Miguel, I've been following your blog posts regarding Flask and RESTful APIs. To echo what everyone has said: thank you! The posts are truly awesome and informative.

    I had a question regarding authentication for the clients. Let's say you have a client using the todo application (from your other tutorials) and you want to store a cookie that has the username and a hash associated with it (to keep anyone from adding their own cookie to log in). Something like : would be fine. However, you wouldn't want to set or retrieve the cookie within your scripts because then then transformation from username/password to cookie would be publicly available. You would want to set and validate the cookie on the server, right? How could you do it from the client? Would an AJAX call be required every time you want to see if the user is validly logged in?

  • #36 Tim said 2014-06-06T04:23:24Z

    this is a great tutorial, and I have gain a lot of information here, I have a question, when you sent then token to the client, is it stored as a cookie in the browser??? if yes, how abut mobile application??? using cookie too?

  • #37 Miguel Grinberg said 2014-06-06T06:01:18Z

    @Tim: if the client is a single-page app then the token can be kept in memory. If you want to emulate the "remember me" then use whatever local storage mechanism the client platform offers. Cookies are valid, a file on disk, etc.

  • #38 Miguel Grinberg said 2014-06-06T06:14:53Z

    @Jonathan: Not sure I understand what you are saying, but note that the function that hashes a password does not need to be kept secret. The key for this to work is that the function cannot be reversed, in other words, that it is not possible to find a function that takes a hash and returns the original password.

    In any case, you are correct in that the server needs to do the verification. And the user needs to accept a "remember me" type option to have his/her password stored in the client, as this is inherently insecure, no matter how much encryption you throw at it.

  • #39 John said 2014-07-11T20:53:14Z

    I have a working sample of this that works great in a test environment, however once I configure Apache to put it in production, the "login_required" function always fails to authenticate. I just get a 401, Unauthorized Access error for any combination of username/passwords attempted. Are there any particular permissions necessary for the libraries to work?

  • #40 André Geraldo dos Santos said 2014-08-19T12:41:16Z

    Hello Miguel

    My name is André Santos, this nice very

    I am developing a server application using flask-restfull concepts and need to distribute the project using virtualenv in shared environment.

    My application server needs to run as a service and I am not finding a way to activate my virtualenv before running the boot in initialization module .

    My server will be accessed by a rest-client application developed in php, is not an integration via WSCGI.

    How should I distribute my application, you can share your experience in this matter?

    I thank you for your attention and waiting your return.

  • #41 Miguel Grinberg said 2014-08-19T15:48:59Z

    @Andre: you do not need to activate the virtual environment, it is enough that you use the python interpreter inside it. For example, if your service starts by running run.py in directory /home/service/run.py and your virtual environment is in /home/service/venv, then you can start your service from /home/service with the command "venv/bin/python run.py".

  • #42 risko sode said 2014-09-19T14:32:07Z

    After user login with HTTP Basic Authentication, how can I get the name of the logged-on user Best,

  • #43 Miguel Grinberg said 2014-09-20T18:37:12Z

    @risko: in the examples shown above the logged user is at g.user.

  • #44 Eugene said 2014-09-23T13:32:40Z

    Hi there, great work!

    I was wondering how can I use Flask to implement a RESTful service for third party clients ? How can this tutorial be modified to achieve this ?

    Thanks!

  • #45 Miguel Grinberg said 2014-09-23T18:07:59Z

    @Eugene: Maybe you mean third party servers, where a third party server sends API requests on behalf of a user? As far as authentication it is pretty standard to use OAuth for this scenario, as this enables the third party server to authenticate and send API requests without having the user's credentials to your API. I would implement this with OAuth2 directly for this, the basic token generation shown in this article can be used, but you would need to add several pieces more, it can be a decent amount of work to do from scratch.

  • #46 Miguel Brito said 2014-09-29T14:51:08Z

    Excellent article! this series have been very helpful to me.

    As you mention in the README.md file, it's possible to generate a new token from an already existing one to extend the expiration time. Do you have any recommendation on how and when to do this?

  • #47 Miguel Grinberg said 2014-09-30T15:47:46Z

    @Miguel: it really depends. Allowing clients to renew the token this way can be seen as a vulnerability, since an attacker that grabs one token now has the ability to renew as well. It is a convenience feature for secure applications, I would not implement this feature on an API that receives requests from unknown clients.

  • #48 Mario said 2014-10-17T13:30:16Z

    I could not make it working over CORS and using jquery (cross domain).

    I changed to jsonp , but it do not pass the correct username and password to flask.

  • #49 Vivek said 2014-10-17T20:06:14Z

    Excellent tutorials as always..but I have a doubt. You said there is no need to hide login credentials if its is between client and api does that mean we can send it in query string or post body itself and need not to do any token base auth ?

    Let say i want to build a web app with a api and multiple clients plus a public api for anybody to make their own clients..In this case what the best way to design api ? a private api for own clients and public api for others ? or is it better to use a a same api for both.

    Thank you

  • #50 Miguel Grinberg said 2014-10-17T21:43:51Z

    @Vivek: if you want to support third-party applications that need to use your API on behalf of your users, then you need OAuth or something similar, because you do not want the user to give credentials to a client written by a third party. An OAuth based API can also be used by your own trusted client, so you don't really need to have two different authentication methods.

Leave a Comment