Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 698
NickAldwin Avatar asked Mar 15 '13 17:03

NickAldwin


People also ask

How do you authenticate API in Flask?

To do this, you need to implement an authentication middleware. Middlewares are created in Flask by creating a decorator; a function can have multiple middlewares, and the order matters a lot. You need to add a secret key to your application; this is what you should pass to JWT.

Is API key enough for authentication?

API keys aren't as secure as authentication tokens (see Security of API keys), but they identify the application or project that's calling an API. They are generated on the project making the call, and you can restrict their use to an environment such as an IP address range, or an Android or iOS app.

Can you use an API without a key?

Starting June 11, 2018, you can no longer use GoogleMaps API without key.

How do I authenticate API key?

Basic Authentication You can pass the API key via Basic Auth as either the username or password. Most implementations pair the API key with a blank value for the unused field (username or password). You will need to base64-encode the 'username:password' content, but most request libraries do this for you.


1 Answers

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 
like image 88
Jeff Ferland Avatar answered Sep 21 '22 19:09

Jeff Ferland