Is there an accepted way to use API keys for authentication in Flask?

NickAldwin picture NickAldwin · Mar 15, 2013 · Viewed 29.3k times · Source

I have a small API that I'd like to add authentication to. I'd like to be able to generate API keys for API consumers; the consumers can then use include the keys with their requests requests.

Is there a Flask library which does something like this? Or is there a typical way to do it? I did a search and I only really came upon this, which doesn't really go very much in depth. I'm looking for a library if there is one.

Answer

Jeff Ferland picture Jeff Ferland · Mar 15, 2013

For authentication keys, create a random value and store that value in a database. random() provides insufficient entropy for things like this, so use os.urandom().

The link you posted to has a very good example of how to handle things with a decorator function. In the decorator function, check the appkey value is set in the request, verify it is valid in the database, and then return the function. If the appkey is invalid, raise AuthenticationError("Invalid appkey") and you're done.

The example you linked to is a bit confusing. I like the demonstration from How to make a chain of function decorators? better.

def checkAppKey(fn):
    def inner(*args, **kwargs): #appkey should be in kwargs
        try:
            AppKey.get(appkey)
        except KeyError:
            raise AuthenticationError("Invalid appkey")
            #Whatever other errors can raise up such as db inaccessible
        #We were able to access that API key, so pass onward.
        #If you know nothing else will use the appkey after this, you can unset it.
        return fn(*args, **kwargs)
    return inner