A Brief Guide on How & Why to Secure API Keys

A comprehensive guide on how & why you should secure your API keys. This guide covers in-depth security risks, API secrets, and more.
Picture of aden.forshaw
aden.forshaw

Applications are ubiquitous. We use them for nearly every facet of our lives. Do you ever wonder how we secure all of this data constantly firing back and forth from server to server?

For instance, how do you know that when you place an order through an app from an online retailer, your payment information isn’t compromised between the merchant and the bank? The answer would depend on if the bank protected its API or not. 

Although there are multiple ways to protect your API, today, we will focus on how to secure your API keys. 

Securing your API keys uses unique code that identifies and authenticates an application call or project. This process then is able to control and monitor who uses the API and how. To determine who can use the API, they must be approved through an authorization process. 

This prevents bad actors from compromising your API, flooding it with bad data, stealing sensitive information, or hijacking the API to turn it against its users. 

Why You Should Pay Attention to Your API Security

Securing API keys should be a priority for your infrastructure. You don’t want to leave sensitive data vulnerable to attack. Below are a few common reasons why API security is indispensable: 

Common Attacks

You’ll need to defend your API against everyday hackers. These bad actors have multiple ways to attack your system. SQL injections and Cross-site Scripting are two prevalent means that hackers use to input malicious code into applications to alter their protocols and operations.

A denial-of-service or a distributed-denial-of-service, DOS and DDOS, respectively, are tactics that bad actors can use to flood your network server with terabytes of traffic until it crashes, rendering the server useless for its clients. Perhaps they will employ a man-in-the-middle attack by inserting themselves into a conversation or data exchange to extract sensitive information. 

These are just a few ways bad actors will attempt to compromise API security. However, there are other, sometimes considered less-malicious reasons why you should secure API keys. 

Staff Turnover 

Another consideration is a change in personnel. Your application contains sensitive information that you don’t want former employees to have continued access to. If you have personnel who have recently left the company, you’ll need to revoke their access, regenerate new API keys and update your applications to use the new keys. 

GitHub 

Developers can accidentally compromise their commit API keys for the different APIs they use in their code repository. It happens to developers of all levels, especially junior ones. Even if they remove the file, the API key will remain in the Git History forever. If the Codebase is ever made public, then the entire history is also made public. Having an easy way to “rotate” an API key is essential (deactivate the old key and create a new one).

Most APIs make the mistake of only allowing their users to create one API key for their accounts. This inevitably creates insecurity as the same key has to be used everywhere, meaning if it is compromised in one place, then it needs to be updated everywhere. 

Client-Side Code

If developers have to create an application based on JavaScript on the client-side, then they may be required to enter an API credential in the header of the request. Bad actors may scan through client-side files and obtain credentials by using script attacks that skim forms, text areas, and fields. After doing so, they can use the stolen credentials to access other login portals and sensitive information. 

Oftentimes, even if developers have to include API credentials in the client-side code, they are confident in their methods to obscure such information. However, hackers can employ tactics to bypass obfuscation and other security methods. The Client-side is where most hackers attempt their attacks. API keys stored directly in the code can be easily exposed to the public.

How to Use API Keys

To understand how API keys are used, we need to understand the fundamentals. 

Basic Rest API Authentication Flow

Earlier, we mentioned authentication, which is a function of API keys. We must also understand API structure to understand this function. The most popular type of API is RESTful. They adhere to the representational state transfer architecture style, known for utilizing HTTP for Web-based API and its flexibility. 

In this authentication, the client sends HTTP requests within the Authorization header, including the word Basic followed by a space and a username/password combination encoded in base64. This is the least secure authentication method because your credentials are not encrypted or hashed.

Secure API Keys in JavaScript 

Authentication API in JavaScript requires you to reveal your API key credentials to use it. However, there is a workaround. You can restrict the API keys, enabling two things to happen. The key will be limited to select API endpoints and can only call those endpoints. Secondly, the key is restricted by domain, ensuring that JavaScript can only make a successful call to an API from a recognized field. 

Secure API Keys in Python

To secure your API keys in Python, you will need to create variables for them and store your code locally in a config.py file that does not get uploaded to a public repository. By including the filename in a .gitignore file, you can exclude the file from being committed to a public repository. 

The .gitignore file will be excluded in git updates. Next, exclude your config.py file by including the config.py in .gitignore. The config.py file and your included API key data will be omitted from your git commits.

API Key Secrets 

Basic Rest API Authentication is standard and lacks encryption, allowing bad actors to view your API credentials. This is where an API secret could prove beneficial.

What is an API Secret? 

If your API keys are identifiers that tell the API which user is trying to gain access, then the API key secret is a way for you to prove you are who you claim to be. The key is the username (tells API who you are), and the secret is the password. 

How to Keep API Secrets a Secret 

To keep your secret protected, never embed your credential secrets in your code or upload your source code to GitHub with the secret embedded within that code. This may allow bad actors to simply lift your credential secrets from your browser using dev tools or enable repository crawlers to extract your credential secrets. 

Generating and Managing Secure API Keys 

Let’s dive into generating, managing, and storing your API keys. 

How are API Keys Generated?

API keys are generated using a secure random generator to create an alphanumeric code designed for cryptography that is not guessable, random, and unique. Afterwards, you should switch the hex encoding to Base64 encoding, or you can edit the length of the key by using hash functions of your choice. The API key code is automatically assigned to the user when the API is registered. 

How to Safely Store API Keys and Structure Them 

Effectively, API keys are passwords that users of a mobile app or website use to gain access to data on an API. Secure storage of API keys is pertinent. 

They must be stored to be accessible to cross-reference against API keys in a request to ensure that they are valid and issued by authorized projects.

The best practice is to store it as a hashed value rather than storing the key in plain text, which is unsecured, or encrypting it, making it nearly impossible to find.

A hashed value ensures that no API keys are leaked even if a bad actor gets access to the infrastructure. It works by the end-user sending the original API key in each API request. The keys are validated by hashing the API key in each request and cross-examining those hashed requests against the previously stored hash value. 

Let’s take a moment to consider the issues with this storage method. 

Usability with API Keys

We are not using the original API key, meaning users will not be able to view it in the hashed storage method. Users must understand that if they lose their API key or do not correctly copy it, they’ll need to generate a new token to access the API. 

Additionally, users will be unable to identify the API keys in your infrastructure should they need to edit or revoke them. You can solve this by adding a prefix of seven characters to your API key, separated by a dot. The prefix can be stored somewhere and displayed in the infrastructure, enabling users to identify which API key is correct. 

How to Secure API Keys

You’ll want to secure your API keys after storing them. Here are a few strategies worth considering:  

API Key Restrictions

When securing API keys with JavaScript, setting URL restrictions on your API Key is a great way to secure your API no matter which scripting language is used. Additionally, you can set daily limit usage of API credentials, preventing hackers from flooding your bandwidth and disrupting site traffic. 

Use an Environment Variable

By using a .env file, your API key secret won’t be visible in the source code. .Env files work well with GitHub because those files can be uploaded and added to a .gitignore file. In doing so, your .env file won’t be committed to GitHub. 

Repository Scanners 

These scanning tools include Git-Hound, GitGuardian, Watchtower, and TruffleHog. They can be used to scan Git commits in repositories on Bitbucket, GitHub, or Gitlab for secrets. These tools deter hackers from obtaining or sharing sensitive information with other repositories.  

Security Key Takeaways 

With the above strategies in mind, it’s time to cover some general best practices for API key security. These can include: 

  • Never insert API keys directly in code. Instead, store them in environment variables or files outside of your application’s source tree
  • Enabling application and API key restrictions 
  • Scheduling the regeneration of your API Keys, especially if your business employs contractors or has staff turnover 
  • Deleting API keys you do not need or use to reduce exposure to malware, spoofing, and other malpractices
  • Always review your code to ensure there are no API keys embedded
  • Never sharing GitHub credentials 

How The Auth API Can Help You Secure API Keys 

The Auth API provides scalable API key management. As a business, you shouldn’t have to worry about how to secure your API keys. Instead, you deserve complete peace of mind when it comes to the integrity of your projects and environments, so you can focus on what matters most, delivering quality products and services to your business. 

  • Enables you to activate, deactivate, or provide API keys from your dashboard or an API call
  • Easily destroy a token and access allowances for rotating team members 
  • Saves time by allowing you to generate or refresh tokens for multiple team members at once  
  • Removes the risk of building your own robust key store. The Auth API features lifecycle management and bad-actor detection, which third-party industry-leading security firms have audited.
  • Monthly auditing via email with detailed information on who has been using your keys. 
  • Anomaly detection and strategization about how to solve the issue 
  • Provides rate limiting for your project or each key to prevent bandwidth flooding 

Ready to see how The Auth API can fit into your tech deck? Book your demo today!

Picture of a blac and white guarding your keys

What safeguards have you implemented to protect your API from malicious actors?

Take the first step today on your journey to secure API access.