There are a couple of ways to do authentication and authorisation, and it's probably a good idea to read a bit about the different standards - for example, https://oauth.net/2/ or https://openid.net/connect/ . But just to give a rough idea of how these things happen: an API key can be as simple as a random string of characters that identify an authentication object in your database. When creating an API key, you: Generate a random string, e.g. a UUID Create an auth object Store the auth object in your database Store the API key in your database and make it point to your auth object via. a foreign key An auth object can look like this: { email: "[email protected]", username: "Johnnyboi", role: "Admin", canAccessApis: [ '/products', '/users', ... ], canDeleteOtherUsers: true, canDeleteOtherAdmins: false } ... you just put whatever information in there that you want. Then, you give that API key to the user and tell them to append it to every request they make to your API. Typically, the API key is included as a header called something like X-API-KEY. Then, in the backend at your API, on every request you: Extract the header in which the API key should be Look up the API key in your database and get the auth object it points to Use the auth object to check if the user is allowed to do what they want to do You typically write middleware for doing this so you don't have to copy that code for every endpoint you have. This is a very simple way of doing it, but will work just fine. Still, I strongly recommend reading up on some more sophisticated ways of doing it, such as OAuth2 or OIDC. Answer from Iklowto on reddit.com
🌐
Google Support
support.google.com › googleapi › answer › 6158862
Setting up API keys - API Console Help
Click Create credentials and then select API key. Note: In addition to reading the instructions on this page, be sure to read Best practices for securely using API keys.
🌐
Reddit
reddit.com › r/learnprogramming › how do i create api keys for my api?
r/learnprogramming on Reddit: How do I create API keys for my API?
June 21, 2021 -

I need to add authentication so that when a user makes a request to the API the API will check if they are able to make requests. I’m not sure how API keys are created or how to make them useable though. Are there any good articles or videos I should watch to learn more about API keys?

Top answer
1 of 3
4
There are a couple of ways to do authentication and authorisation, and it's probably a good idea to read a bit about the different standards - for example, https://oauth.net/2/ or https://openid.net/connect/ . But just to give a rough idea of how these things happen: an API key can be as simple as a random string of characters that identify an authentication object in your database. When creating an API key, you: Generate a random string, e.g. a UUID Create an auth object Store the auth object in your database Store the API key in your database and make it point to your auth object via. a foreign key An auth object can look like this: { email: "[email protected]", username: "Johnnyboi", role: "Admin", canAccessApis: [ '/products', '/users', ... ], canDeleteOtherUsers: true, canDeleteOtherAdmins: false } ... you just put whatever information in there that you want. Then, you give that API key to the user and tell them to append it to every request they make to your API. Typically, the API key is included as a header called something like X-API-KEY. Then, in the backend at your API, on every request you: Extract the header in which the API key should be Look up the API key in your database and get the auth object it points to Use the auth object to check if the user is allowed to do what they want to do You typically write middleware for doing this so you don't have to copy that code for every endpoint you have. This is a very simple way of doing it, but will work just fine. Still, I strongly recommend reading up on some more sophisticated ways of doing it, such as OAuth2 or OIDC.
2 of 3
1
A simple way is to generate them as needed from a combination of a UUID and some extra (truly) random data. For example, I could make a UUID from the date and a 32-bit sequence number: YYYYMMDDSSSSSSSS Then use a truly random source (with entropy) to add like 96 bits (or more!) to that: YYYYMMDDSSSSSSSSRRRRRRRRRRRR Finally I would add a check digit or two so I can use javascript/php/whatever to verify validity without a db hit: YYYYMMDDSSSSSSSSRRRRRRRRRRRRCC Now you just have to make sure to protect the ever loving hell out of the database table that matches an internal ID number to each API key. You may wish to include a version or timestamp with that table so you can invalidate old keys, etc. When I would make registration keys for games I would include even more embedded info in the key, and I would jumble it deterministically. The program I used to generate them was written and used on an air-gapped machine and I would copy over batches of keys using a DVD burner. The key disks went into a safe. Other than all that it's just like any other authentication method. You use session handling code. The big thing is do not store your API keys in the same table as your customer data. Maybe not even the same database if perms are easier that way. I wouldn't even use the customer ID number in the table, instead I would have a third table with one customer id associated with many key id's. The idea being that a customer might have different level APIs for different aspects of their portal, and a hacker would have to breach all three databases to link an API key with that customer. For research: database security, true random numbers, check digits, possibly obfuscation, and session handling.
Top answer
1 of 12
94

Use a random number generator designed for cryptography. Then base-64 encode the number.

This is a C# example:

var key = new byte[32];
using (var generator = RandomNumberGenerator.Create())
    generator.GetBytes(key);
string apiKey = Convert.ToBase64String(key);
2 of 12
40

API keys need to have the properties that they:

  • uniquely identify an authorized API user -- the "key" part of "API key"
  • authenticate that user -- cannot be guessed/forged
  • can be revoked if a user misbehaves -- typically they key into a database that can have a record deleted.

Typically you will have thousands or millions of API keys not billions, so they do not need to:

  • Reliably store information about the API user because that can be stored in your database.

As such, one way to generate an API key is to take two pieces of information:

  1. a serial number to guarantee uniqueness
  2. enough random bits to pad out the key

and sign them using a private secret.

The counter guarantees that they uniquely identify the user, and the signing prevents forgery. Revocability requires checking that the key is still valid in the database before doing anything that requires API-key authorization.

A good GUID generator is a pretty good approximation of an incremented counter if you need to generate keys from multiple data centers or don't have otherwise a good distributed way to assign serial numbers.


or a hash of a random string

Hashing doesn't prevent forgery. Signing is what guarantees that the key came from you.

🌐
Stripe
docs.stripe.com › keys
API keys | Stripe Documentation
You can access your v1 API keys on the API keys tab. By default, all accounts have a total of four API keys:
🌐
Google
developers.google.com › google maps platform › web services › places api › set up the places api (new)
Set up the Places API (New) | Google for Developers
To create one, navigate to the Google Maps Platform Credentials page, click \"Create credentials,\" then \"API key,\" and close the dialog.
🌐
Google AI
ai.google.dev › gemini api › using gemini api keys
Using Gemini API keys | Google AI for Developers
If you don't have any projects created yet, you must either create a new project or import one from Google Cloud into Google AI Studio. The Projects page in Google AI Studio will display all keys that have sufficient permission to use the Gemini API.
🌐
Steam Community
steamcommunity.com › discussions › forum › 1 › 3047235828269633221
How to get my APi Key :: Help and Tips
Originally posted by Supafly:https://steamcommunity.com/dev/apikey I open the link and in link tekst is You will be granted access to Steam Web API keys when you have games in your Steam account.
Find elsewhere
🌐
OpenAI Developer Community
community.openai.com › api
How do I get my API key? - API - OpenAI Developer Community
January 3, 2023 - I see in every catagory of using the A.I. within the perimeters it states, insert your API key. Where do I get an API key?
🌐
Google
developers.google.com › google maps platform › web › maps embed api › set up the maps embed api
Set up the Maps Embed API | Google for Developers
To create one, go to the Google Maps Platform Credentials page and select \"Create credentials\" then \"API key.\" Restrict your key via the Credentials page, selecting \"HTTP referrers\" for application restrictions and choosing specific APIs ...
🌐
StrongDM
strongdm.com › tools › api-key-generator
API Key Generator: Random, Online, Free
Use our free API Key Generator to create secure, random, and unique keys for your apps and integrations—no sign-up required.
🌐
Esri Developer
developers.arcgis.com › documentation › security-and-authentication › api-key-authentication › tutorials › create-an-api-key
Tutorial: Create an API key | Documentation | Esri Developer
You use your portal to create and manage items, including API key credentials. In your web browser, go to your ArcGIS Enterprise portal and sign in to your portal with your ArcGIS Enterprise account.
🌐
Google Cloud
cloud.google.com › application development › google cloud sdk › authentication › manage api keys
Manage API keys | Authentication | Google Cloud Documentation
The key ID can't be used to access APIs. The key ID can be found in the URL of the key's edit page in the Google Cloud console. You can also get the key ID by using the Google Cloud CLI to list the keys in your project.
🌐
SheCodes
shecodes.io › athena › 77847-where-can-i-find-an-api-key
[API] - Where can I find an API key? - SheCodes Athena - AI | SheCodes
Learn where to find an API key and the process to obtain it from the API provider's website or platform.
🌐
Google
developers.google.com › google maps platform › web › maps javascript api › set up the maps javascript api
Set up the Maps JavaScript API | Google for Developers
To create an API key, navigate to the Google Maps Platform Credentials page and select \"Create credentials \\\u003e API key.\" Restricting API keys to specific applications and APIs is strongly recommended for security and to prevent financial ...
🌐
Qlik
qlik.dev › authenticate › api-key › generate-your-first-api-key
Generate your first API key | Qlik Developer Portal
Provide a description and set an expiration time for the API key. Click Generate to create the key.
🌐
Google
docs.cloud.google.com › application development › api keys api documentation › creating and managing api keys
Creating and managing API keys | API Keys API Documentation | Google Cloud Documentation
The keyString field contains the string that you send to the APIs that require an API key. The keyString maps to the API key field in the Google Cloud console. You can call the GetKeyString method to get the keyString for an API key.
🌐
Google AI Studio
aistudio.google.com › app › apikey
Google AI Studio API Key
Sign in · Use your Google Account · Not your computer? Use Guest mode to sign in privately. Learn more about using Guest mode · Create account
🌐
OpenAI
platform.openai.com › api-keys
create an OpenAI API key
Explore developer resources, tutorials, API docs, and dynamic examples to get the most out of OpenAI's platform.
🌐
The Full-Stack Blog
coding-boot-camp.github.io › full-stack › apis › how-to-use-api-keys
How to Use API Keys | The Full-Stack Blog
Under Create Key, give your API key a name that's unique to your project, then click the Generate button. This will take you to a page that lists any keys that you've created. They should look like a random string of 32 characters.