API Authentication: JWT , API Keys & OAuth for Developers

Home >> TECHNOLOGY >> API Authentication: JWT , API Keys & OAuth for Developers
Share

I have leaked an API key to GitHub previously. Sat up spent Sunday panicky turning credentials and reviewing access logs. The error saved me a whole library on API authentication than any tutorial would.

Authentication is no longer an option in the construction of APIs or in the incorporation of APIs. Being a first-time dev shipping an endpoint or a security auditor, this guide helps to go through the real thing. No nonsense, it is what I would have loved to be heard 3 years ago.

API Authentication Fundamentals

The following is the bargain: authentication gives a reply to the question: who are you? and wording is permission “what can thou? The majority of API security attacks occur due to developers confusing and absent-minded in the implementation.

There are three broad descriptions in production that I have witnessed:

API Keys work like passwords. You come up with some kind of string, send it in requests and the server authenticates it. It is a simple that is very dangerous, though, when you are not careful.

The JWT (JSON Web Tokens) is akin to tamper poor identity cards. They contain data of the user and cannot be altered without being detected. Great for stateless systems.

OAuth 2.0 is the valet key of auth. You are granting restricted access to the machine without providing it with the master key. Ideal where the third parties require regulated access to your API.

Each has its place. The secret is to be able to decide which of them fits your use.

API Keys: When to Use and How to Secure

I continue to utilize API keys on the internal services and basic integrations. They are not wicked–still, they are abused.

When API keys make sense:

  • Internal service-to-service communication of your own services.
  • Public read-only data (map, weather, etc. APIs, quotation of stock, etc.)
  • Lighting prototypes use both extremes.

When they don’t:

  • Anything touching user data
  • Mobile lean code (keys can be ripped out of compiled Android code).
  • Card-Third parties where you require fine controls.

Here’s how I secure them now:

First, never hardcode keys. I was able to discover this in an expensive manner. Make use of environment variables and secret man. I use them in my projects that are created in .NET and stored in Azure Key Vault and retrieve them at the run-time.

Second, rotate regularly. Set calendar reminders. I change critical keys after every 90 days and my process is documented as time-consuming of 10 minutes.

Third, scope them down. When your API provider is allowing you to generate read-only keys, or restrict the keys to a particular IP address, do it. I used to have a key which could only enter two endpoints- in case, when it leaked there was limit to the damage.

Monitor usage patterns. Drastic increase in new IP requests? Your canary in the coal mines.

JWT Implementation in APIs

The Aha moment that happened to me was when I got to know how it was constituted. It consists of three parts divided by dots; header.payload.signature.

The header reflects on which algorithm it was signed with. The message body is your data (user-identifier, authorization, expires). The signature can attest to the fact that no one has touched it.

What I like about JWT: You do not have to have data base look up with each request. All the identity can be found on the token. This shortened the time of my APIs and eased my architecture.

The gotchas I hit: One can not take back a JWT until it expired. My mine was set to a 15 minutes expiration on access tokens. This is not noticed by users since they are automatically retrieved and replaced by new refresh tokens (stored securely).

Should not have delicate information in a payload. JWTs are not encrypted but coded. They can be decoded and read by anybody. I one time did see a JWT containing an email address and a password reset token as the plaintext. Don’t be that developer.

The following is my current configuration: API calls are available by short-lasting access-tokens (15 min) and longer groups (7 days) that are prepared in HttpOnly cookies. Once the expiration of the access token, the refresh token receives a new one. Once one steals an access token, he/she has limited time up to 15 minutes.

Endlessly, specifications Turn off the none algorithm, not just as a validation. Attackers can strip signatures off with this ancient debugging option. All libraries of JWT have the choice of blocking it- turn it on.

OAuth 2.0 for Third-Party Integrations

OAuth puzzled me over the course of months before I came to view it with the perspective of not as authentication but as the delegation of permission.

When you get on a web site and click on the GoogleLogin button, you are not entering your Google password into the box. You are telling Google, “You know, Google I would like this site to have access to my email address and profile picture. That’s OAuth.

Most web applications are supposed to be using the Authorization Code Flow. This is how it is done practice wise:

There is a redirection of the user to the OAuth provider (Google, GitHub, or whatever) with your app. On there they do not walk in on your site, they walk on theirs. The provider rates back a temporary code. The code is traded on your backend in exchange off an access token. It is now possible to make API calls on his behalf.

I used this because one of the projects had to use Google Drive. At the most important was knowing scores termed rights that you require. I requested only drive.readonly, since I did not have to write anything. Ask as little as possible permissions.

Common mistakes I’ve made:

LocalStorage of tokens was prone to the XSS attack. I save them now in HttpOnly cookies where JavaScript has no access to it.

Failure to validate the parameter of the state. This happens when CSRF attacks are prevented using this random string. Create one and redirect it to the OAuth provider, store in it and when a user comes back, validate and verify if it is the same one.

The Implicit Flow was used as it appeared easier. It has been depreciated correctly since it is quite useful to replicate the tokens in the URLs as the browser history and referers are leaked.

OAuth 2.1 is sweeping such problems away. PKCE (Proof Key for Code Exchange) is now compulsory and this prevents attacks of interception of the codes. Today when you are implementing OAuth, you should use the 2.1 spec.

API Security Checklist

The following are what I look at when an API is about to be launched:

Authentication layer:

  • No embedded keys to the system (grep codes deployed to main)
  • dev keys should not be able to work in production secrets that are environment specific.
  • Limit auth endpoint rate (prevent brute force attacks)

Token management:

  • Expiry of access tokens (Expiry of access tokens in short bursts).
  • Insecure storage of refresh tokens (Not secure back end storage)
  • Authentication of tokens within all secured points.

Transport security:

  • Encrypt all the things (Free) Recently? HTTPS.
  • HSTS headers Enabled (forces HTTPS);
  • Mobile app certificate pinning.

Access control:

  • Minimal access control (users access as little as possible)
  • Effective validations of the OAuth tokens.
  • Checking fed to all endpoints (do not trust client data)

Monitoring:

  • Failed log in attempts.
  • Shiala on abnormal accesses.
  • Frequent API endpoint security controls.

This is my checklist that I have kept in the Notion and I revise it prior to every release.

Protecting API Credentials in CI/CD Pipelines

This is the area of most of the leaks. To deploy your pipeline, run tests, and integrate with services, your CI/CD pipeline requires API keys. Yet it is the case that the pipeline logs can be seen by the entire staff.

What I do now:

Take secret management out of your CI/CD platform. GitHub Actions Industries has encrypted secrets. GitLab contains secure variables. Azure DevOps contains variant groups which are connected to Key Vault. Credentialing It is recommended that you do not add credentials to your YAML files in a pipeline.

Limit Scope- Branch/ Environment secrets. My API keys can be used in the production pipeline, and only in the production pipeline. And even in the case that somebody gets into my dev environment, he or she will not be able to reach production.

Mask secrets in logs. This is verified by most platforms although done automatically. I have also encountered API keys displayed as error messages that were not masked out.

Change the secrets employed in CI/CD on a regular basis, as production keys do. I treat them as equal risk.
Work on limited conditions of service accounts. My deployment pipeline has an account that not only allows deployment to particular resources, but also does not access the data about customers or edit other infrastructure.

Wrapping This Up

API authentication, however, is not as nightmareish as it appears to be. Begin by knowing what is well done by each method. Keywords toward straightforward inner things. JWT with the control of both ends stateless APIs. OAuth on limited access by third parties.

It is not choosing something that is the most secure, but choosing what fits in your particular situation and using it well. I’ve encountered a flawless deployment of OAuth and JWT systems that were ended up being entirely flawed. The means are given the second place to the action.

When you are new, you can start with API keys regarding internal services. Become accustomed to secret administration, movement. Is that the case then take to JWT on your APIs. Last but not least, address OAuth in the instances of the third-party integrations. And do not please hard code credentials. Establish appropriate secrets management nowadays. Your future will be glad (as well as your security team).

Read:

Token-Based Authentication: JWT , Session Tokens & Refresh Tokens

Multi-Factor Authentication (MFA) Explained: Types & Implementation

Leave a Reply

Your email address will not be published. Required fields are marked *