How to generate an API key
Posted by Shmifful@reddit | learnprogramming | View on Reddit | 4 comments
I am trying to build an API for a recommendation engine with Python and FastAPI, but I realised that FastAPI doesn't have any built-in function to generate an API key. So far, I've only built frontend apps and relied on cloud services to handle the backend, and obviously getting access to their services using an API. Isn't an API just a random string of characters? How would you securely store it on the server-side?
Powerful-Ad9392@reddit
just hard code `abc123
Consibl@reddit
Generate a random string with good entropy.
Generate some random salt and store that.
Hash the two together and store that.
Share the first random string with the user and don’t store it.
Buttleston@reddit
Instead of rolling your own I would probably just use bcrypt to store the hashed version. Use the same secret for all your api keys so that it's easy to look up. You don't really need to work about a salt-per-user because you won't have any duplicate api keys, and afaik using unique salts is mostly used to keep people from recognizing that multiple accounts have the same password.
IVIichaelD@reddit
I think ideally you would not want to be storing the key directly in your database, you would want to be storing a hash (same as you would a password, there are tutorials online to do this).
However, that being said, personally I say you should do this last. For now just hardcore a key in some file ignored by git so you can keep momentum through the fun parts where you’ll get the best learning.