Best practices for building secure API Keys (2024)

/ #api
Best practices for building secure API Keys (1)
freeCodeCamp
Best practices for building secure API Keys (2)

By Ramesh Lingappa

We all know how valuable APIs are. They’re the gateway to exploring other services, integrating with them, and building great solutions faster.

You might have built or are thinking of building APIs for other developers to use. An API needs some form of authentication to provide authorised access to the data it returns.

There are several authentication standards available today such as API Keys, OAuth, JWT, etc.

In this article, we’ll look at how to correctly manage API Keys to access APIs.

So Why API Keys?

API Keys are simple to use, they’re short, static, and don’t expire unless revoked. They provide an easy way for multiple services to communicate.

If you provide an API for your clients to consume, it’s essential for you to build it in the right way.

Let’s get started, and I’ll show you how to build API Keys the right way.

API Key Generation

Since the API key itself is an identity by which to identify the application or the user, it needs to be unique, random and non-guessable. API keys that are generated must also use Alphanumeric and special characters. An example of such an API key is zaCELgL.0imfnc8mVLWwsAawjYr4Rx-Af50DDqtlx.

Secure API Key Storage

Since the API key provides direct access to data, it’s pretty much like a password that a user of a web or mobile app provides to gain access to the same data.

Think about it. The reason we need to store API keys is to make sure that the API key in the request is valid and issued by us (just like a password).

We don’t need to know the raw API key, but just need to validate that the key is correct. So instead of storing the key in plain text (bad) or encrypting it, we should store it as a hashed value within our database.

A hashed value means that even if someone gains unauthorised access to our database, no API keys are leaked and it’s all safe. The end user would send the raw API key in each API request, and we can validate it by hashing the API key in the request and compare the hashed key with the hash stored within our database. Here is a rough implementation of it in Java:

In the code above, the primary key will be a combination of the prefix and the hash of the API key {prefix}.{hash_of_whole_api_key}.

But hold on, there is more. Storing a hashed value brings specific usability problems. Let’s address those now.

Presenting the API Key to users

Since we don’t store the original API key, we can show it only once to the user, at the time of creation. So be sure to alert users that it cannot be retrieved again, and they need to generate a new token if they forget to copy the API key and store it safely. You can do something like this:

Best practices for building secure API Keys (3)Displaying generated API Key with an alert message

How users can identify a generated API Key later

Another problem is how users identify the right API key in your console if they need to edit or revoke it. This can be solved by adding a prefix to the API key. Notice in the picture above the first 7 characters (that’s our prefix), separated by the dot.

Now you can store this prefix in the database and display it in the console so users are able to quickly identify the right API key entry, like this:

Best practices for building secure API Keys (4)API Key management console

Don’t give the API Key all the power

One common mistake that API key providers make is providing one key to access everything, since it’s easy to manage. Don’t do that. Assume that a user just needs to read an email, and generates an API key. But that key now has full access to other services, including deleting records in the database.

The right approach is to allow the end users to properly restrict API Key access and choose specific actions that an API key can carry out. This can be done by providing scopes, where each scope represents a specific permission.

For example,

  • if you need an API key to just send emails, you can generate an API key with the scope as “email.send”
  • if the end user has multiple servers and each carries out a specific action, then a separate API key can be generated with a specific scope.

So while creating the API key, allow users to select what access that API key should have, as in the image below.

Best practices for building secure API Keys (5)

This way users can generate multiple API keys, each with specific rules of access for better security. And when an API request is received, you can check if the API Key has the right scope to access that API. Now the database looks something like this:

Best practices for building secure API Keys (6)API Key database entity

Rate limiting API keys

Yes, you might already know it, but it is important to rate limit requests made with specific API Keys to ensure no bad actor can take down your API servers or cause performance issues that affect your other customers. Having a proper rate limiting and monitoring solution keeps the API service healthy.

Conclusion

API keys, when built right, are still a great way to communicate with another server. As we reviewed in this article, following certain practices offers benefits to both API consumers and API providers. Hope this helps you.

Happy Securing your APIs!

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

Best practices for building secure API Keys (7)
freeCodeCamp

Learn to code. Build projects. Earn certifications—All for free.

If you read this far, thank the author to show them you care.

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

ADVERTIsem*nT

Best practices for building secure API Keys (2024)

FAQs

What are the security best practices for API keys? ›

  • Always use a unique API key for each team member on your account. ...
  • Never deploy your key in client-side environments like browsers or mobile apps. ...
  • Never commit your key to your repository. ...
  • Use Environment Variables in place of your API key. ...
  • Use a Key Management Service.

What is the safest way to store API key? ›

Keep API keys isolated from the main code and away from the public eye by storing them in environmental variables. Always keep API keys in safe key management solutions for storage. Make sure that the keys are encrypted both in transit and at rest. Alternate your API keys regularly to minimize exposure concerns.

How do I create a secure API key? ›

To generate a platform API key:
  1. Log in to the web client.
  2. From the toolbar, click your avatar.
  3. Click Profile and settings.
  4. Click API key > Generate new key.
  5. Click Generate.
  6. Click Copy and save your key somewhere safe. You cannot recover this key if you lose it.

Which are two best practices used to secure APIs? ›

How to secure an API
  • Implement authentication methods: Implement authentication mechanisms such as OAuth, API keys, or tokens. ...
  • Encrypt communications: Transmit data over HTTPS to encrypt data during transit, safeguarding it from eavesdropping and tampering.
Aug 30, 2024

Should API keys be encrypted? ›

Storing API keys directly in your database is bad practice and not secure. They should be hashed and/or encrypted first before being stored.

Is OAuth more secure than API key? ›

While the API key mechanism is easy and well understood, OAuth provides an alternative solution, considered more secure and better suitable to support a large number of users. OAuth is a way to separate the Authentication Process from the Access to the Resource and therefore limit the exposure of the credentials.

Which way should be used to safely store the API keys? ›

Do not store API keys in files inside your application's source tree: If you store API keys in files, keep the files outside your application's source tree to help ensure your keys do not end up in your source code control system.

Should I store API keys in database? ›

Storing API keys directly in your code is generally not recommended due to the potential security risks. If your code is ever shared or becomes publicly accessible, anyone who sees the API key can use it, potentially leading to abuse or a security breach.

How to keep API secure? ›

API Security: Authorization, Rate Limiting, and Twelve Ways to Protect APIs
  1. Implement Strong Authentication Mechanisms. ...
  2. Ensure Strong Authorization Practices. ...
  3. Validate Inputs and Responses. ...
  4. Rate Limiting. ...
  5. Encrypt Data Transmitted over APIs. ...
  6. Monitoring and Logging. ...
  7. Perform Regular API Security Testing.
Nov 3, 2023

What's the best approach for generating a new API key? ›

As such, one way to generate an API key is to take two pieces of information:
  • a serial number to guarantee uniqueness.
  • enough random bits to pad out the key.
Jan 19, 2013

Should API keys be stored hashed? ›

We should have API keys be available/displayable only at creation. Then we should store a hash of the value in the database. When an API key is received, we'd hash it and then compare that value to the one in the database. If they match, it is a correct API key.

Can I create my own API key? ›

To create your application's API key:
  1. Go to the API Console.
  2. From the projects list, select a project or create a new one.
  3. If the APIs & services page isn't already open, open the left side menu and select APIs & services.
  4. On the left, choose Credentials.
  5. Click Create credentials and then select API key.

Which is the most secure way to use an API key? ›

Recommended for all API key uses
  1. Restrict your API keys.
  2. Use separate API keys for each app.
  3. Delete unused API keys.
  4. Check your API key usage.
  5. Be careful when regenerating API keys.
  6. Protect apps using Static Web APIs.
  7. Protect apps using web services.
  8. Protect mobile apps using web Service or Static Web APIs.

How do I securely authenticate an API? ›

4 Secure API Authentication Methods
  1. API Keys. API Keys are secret tokens used to authenticate API requests. ...
  2. OAuth 2.0. OAuth 2.0 is an authorization protocol that gives API users access to a service without sharing their passwords. ...
  3. HTTP Authentication Schemes (Basic & Bearer) ...
  4. JWT Authentication (JSON Web Token)
Feb 1, 2023

How to secure an API without authentication? ›

API Without Authentication: Risks and Solutions
  1. Implement Strong Authentication Methods.
  2. Enforce Role-Based Access Controls (RBAC)
  3. Implement Multi-Factor Authentication (MFA)
  4. Encrypt Sensitive Data.
  5. Monitor and Log API Activities.
  6. Regularly Update and Patch APIs.
Jan 3, 2024

What is the most secure method to transmit an API key? ›

Don't share API keys through email. Always use HTTPS/SSL for your API requests — some APIs won't field your request if you're not using it.

Which way should be used to safely the API key? ›

Do not store API keys in files inside your application's source tree: If you store API keys in files, keep the files outside your application's source tree to help ensure your keys do not end up in your source code control system.

What is the best practice for API key rotation? ›

How often should you rotate API keys? As a best practice, you should rotate API keys at least every 90 days.

Top Articles
How would I report a drone operator potentially violating the FAA rules or regulations?
Bitcoin Has a Regulation Problem
Drury Inn & Suites Bowling Green
Asist Liberty
Robot or human?
Google Sites Classroom 6X
Big Spring Skip The Games
Caroline Cps.powerschool.com
Unlocking the Enigmatic Tonicamille: A Journey from Small Town to Social Media Stardom
craigslist: south coast jobs, apartments, for sale, services, community, and events
Pike County Buy Sale And Trade
Kostenlose Games: Die besten Free to play Spiele 2024 - Update mit einem legendären Shooter
Vocabulario A Level 2 Pp 36 40 Answers Key
123 Movies Babylon
Comenity Credit Card Guide 2024: Things To Know And Alternatives
Missing 2023 Showtimes Near Landmark Cinemas Peoria
Miami Valley Hospital Central Scheduling
Log in or sign up to view
Craigslist Mt Pleasant Sc
Craigslist West Valley
Why Does Lawrence Jones Have Ptsd
Pokemon Unbound Shiny Stone Location
Toyota Camry Hybrid Long Term Review: A Big Luxury Sedan With Hatchback Efficiency
Woodmont Place At Palmer Resident Portal
Raw Manga 1000
Skidware Project Mugetsu
Log in to your MyChart account
Little Einsteins Transcript
What Is Opm1 Treas 310 Deposit
Wheeling Matinee Results
Armor Crushing Weapon Crossword Clue
The Hoplite Revolution and the Rise of the Polis
Stolen Touches Neva Altaj Read Online Free
Myhrconnect Kp
Adecco Check Stubs
Bee And Willow Bar Cart
Selfservice Bright Lending
Why Holly Gibney Is One of TV's Best Protagonists
Magicseaweed Capitola
The Minneapolis Journal from Minneapolis, Minnesota
Mixer grinder buying guide: Everything you need to know before choosing between a traditional and bullet mixer grinder
Best Restaurants West Bend
Costco Gas Foster City
Sechrest Davis Funeral Home High Point Nc
Senior Houses For Sale Near Me
Craigslist Houses For Rent Little River Sc
Streameast Io Soccer
Access to Delta Websites for Retirees
Minecraft: Piglin Trade List (What Can You Get & How)
Ciara Rose Scalia-Hirschman
Deviantart Rwby
Craigslist Charlestown Indiana
Latest Posts
Article information

Author: Reed Wilderman

Last Updated:

Views: 6178

Rating: 4.1 / 5 (52 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Reed Wilderman

Birthday: 1992-06-14

Address: 998 Estell Village, Lake Oscarberg, SD 48713-6877

Phone: +21813267449721

Job: Technology Engineer

Hobby: Swimming, Do it yourself, Beekeeping, Lapidary, Cosplaying, Hiking, Graffiti

Introduction: My name is Reed Wilderman, I am a faithful, bright, lucky, adventurous, lively, rich, vast person who loves writing and wants to share my knowledge and understanding with you.