JWT vs API Key Auth for Machine to Machine APIs | Zuplo Blog (2024)

Designed for Developers, Made for the EdgeStart freeBook a demoRead docs

Authorizing other services (i.e. "machines") - sometimes called M2M - to callyour API is typically done with either JWT tokens or API Keys. The reason to useone or the other varies by use case. This post will explain the pros and cons ofeach and suggest when each one is a good fit for securing your API.

JWT authentication typically uses an OAuth 2.0 identity provider such as Auth0,AWS Cognito, etc. The identity provider issues tokens after validating theclients are who they say they are.

JWT vs API Key Auth for Machine to Machine APIs | Zuplo Blog (2)

When the client sends a request to the API it includes the JWT in the request'sAuthorization header. The API then validates the JWT to be authentic and usesthe information in the JWT to identify the client. Typically the JWT contains asub parameter that identifies the client. The token also includes a audparameter that specifies which API the token can call.

JWT tokens can be issued with any length of expiration time, but it is typicalfor tokens to expire in a short period, such as one hour.

JWT auth with OAuth uses theClient Credentialsflow on the identity server. Each client that will call the API is issued aClient Id and a Client Secret - think of these values like a username andpassword. The client uses these values to request an access token they use tocall the API. In code, the client credentials flow looks like the followingexample.

Request

curl --request POST \ --url 'https://YOUR_DOMAIN/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=client_credentials \ --data client_id=YOUR_CLIENT_ID \ --data client_secret=YOUR_CLIENT_SECRET \ --data audience=YOUR_API_IDENTIFIER

Response

{ "access_token": "eyJz93a...k4laUWw", "token_type": "Bearer", "expires_in": 86400}

Considerations of Machine-to-Machine JWT Auth#

JWT-based API auth is a good choice for securing microservices within anorganization, or sharing APIs with certain types of external clients.

  • JWT tokens are typically not revokable. To revoke a JWT token you typicallyhave to roll the secrets of that client - this will disable ALL JWT tokenscurrently issued.
  • Permissions with JWT tokens are managed at the identity provider level,meaning that all tokens issued for the same client will have the samepermissions.
  • JWT tokens are static; permissions, expiration time, or other propertiescannot change once the token is issued.
  • When JWT tokens expire, the consumer must request a new token using the ClientID and Secret value.
  • Identity Providers often charge based on the number of tokens issued.
  • The contents of a JWT token are visible to anyone, they can be decoded usingpublic tools like jwt.io

API Key Authentication#

With API Key authentication, each client receives a unique secret key. UnlikeJWT tokens, the key itself doesn't contain any actual data, it is simply anopaque unique string associated with the client. Furthermore, there is nostandard protocol for API Key authentication like OAuth, etc., so eachimplementation can differ.

Ideally, an API using key-based authentication offers the API consumer theability to manage their keys. For example, an API Gateway could offer aself-serve portal where end-users issue their own tokens and critically canrevoke old, and create replacement keys on demand. Tokens can be issued withvarious permissions and with custom expirations times.

A typical API Key authentication system will validate each key as it comes inwith a request. If the key is valid, then data is returned with that key -typically information about their identity and permissions.

// pseudo-code to check key and get metadatafunction myApiHandler(request) { const apiKey = request.headers.get("API-Key"); const apiKeyInfo = apiKeyService.validate(apiKey);  if (!apiKeyInfo.isValid) { return new Response("Unauthorized", { status: 401, }); }  // Check various properties of the api key info if (apiKeyInfo.accountId) { // ... }}

Or, when using Zuplo's API Key system:

export default async function (request: ZuploRequest) { // policy has already enforced that user must // be authenticated if (request.user.data.accountId) { // ... }}

Considerations of API Key Auth#

The main difference between API Key auth and JWT token auth is that the JWTToken is self-contained - the information asserted by the token is in the token.Whereas with an API Key the asserted information is stored in an externalsystem. The externalization of assertion data makes API Keys more flexible forcertain scenarios.

  • API Keys tend to be easier to work with for your partners, that's one of thereasons why businesses like Stripe, Twilio and Airtable use API Keys for theirpublic API.
  • Individual API Keys can be revoked - rather than resetting a wholeclient/customer.
  • Permissions and expiration times of keys can be changed even after they areissued.
  • API keys are opaque, so no details of your implementation or scoping systemare visible externally.
  • Because the key doesn't contain any information, the associated data for eachkey can effectively be limitless. For example, an API Key Authenticationsystem could also assert that a particular token is allowed to access aparticular account.
  • API Keys can be issued without expirations and revoked only when needed (i.e.,a customer cancels their account).

Both JWT authentication and API Key authentication are good options whenbuilding a secure API. Each has benefits and drawbacks. JWT authentication isstandardized and there are libraries you can use to implement API keyauthentication quickly. However it is typically more complex for your APIconsumers.

API Key authentication, on the other hand, tends to be extremely simple fordevelopers to understand and implement and is popular with B2B SaaS businesses.

However, it can be non-trivial to implement an API Key management solution. Youneed to securely store (or hash) the API Keys, have a developer-facing UI whereconsumers can self-serve and roll keys on demand. We've written about our [BestPractices for API Key Authentication] (/blog/2022/12/01/api-key-authentication)developed from building Zuplo and our team's collective experience at companieslike Microsoft, Facebook, Auth0, and Stripe.

About Zuplo#

Zuplo is a serverless API Gateway, designed for developers. With Zuplo you cansecure your API with API Keys, add rate limiting, get developer documentation,and more in record time. Try Zuplo Free

JWT vs API Key Auth for Machine to Machine APIs | Zuplo Blog (2024)

FAQs

When to use API key vs JWT? ›

Typically, the API key provides only application-level security, giving every user the same access; whereas the JWT token provides user-level access. A JWT token can contain information like its expiration date and a user identifier to determine the rights of the user across the entire ecosystem.

Which is better than JWT authentication? ›

Paseto (Platform-Agnostic Security Tokens) has emerged as a better solution, directly addressing the shortcomings of JWT. Designed with a focus on security, Paseto provides a more secure foundation for token-based authentication by mitigating vulnerabilities and enforcing secure defaults.

What is the difference between API key authentication and token authentication? ›

API keys are for projects, authentication is for users

The main distinction between these two is: API keys identify the calling project — the application or site — making the call to an API. Authentication tokens identify a user — the person — that is using the app or site.

What is the difference between JWT and authorization? ›

OAuth is used for authorization to access resources on behalf of an owner, while JWT is used for authentication and exchanging information. When should I use OAuth vs JWT? You should use OAuth when you want to delegate user authorization and access to a third-party application.

Should you use JWT for authentication? ›

Use traditional session-based authentication. It's more secure and flexible than JWT. JWT is a good fit for cases/situations where you want to issue a one-time token to be used for a specific purpose.

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

Avoid Client-Side Exposure

Storing API keys in client-side code such as JavaScript is an insecure practice as it makes them easily accessible to malicious actors. To ensure the security of your API keys, never embed them in URLs or client-side code. Instead, keep them securely stored server-side to protect your data.

What are the disadvantages of JWT authentication? ›

Once a JWT is issued, there is no straightforward way to invalidate it before its expiration time. This can pose a problem if a user logs out or if their privileges need to be revoked due to a security concern. To address this weakness, developers must implement additional mechanisms for token revocation.

When not to use JWT? ›

We already established that storing sensitive data inside localStorage is a bad idea. To reiterate, whatever you do, don't store a JWT in localStorage (or sessionStorage). If any of the third-party scripts you include in your page are compromised, it can access all your users' tokens.

Is JWT obsolete? ›

The JWT app type will be completely deprecated as of June 2023. New and current users have 12 months to migrate their JWT based solutions to the Server-to-Server OAuth app type.

What is the best authentication for API? ›

Best API authentication protocols
  1. OAuth (Open Authorization) OAuth is an industry-standard authentication protocol that allows secure access to resources on behalf of a user or application. ...
  2. Bearer tokens. Bearer tokens are a simple way to authenticate API requests. ...
  3. API keys. ...
  4. JSON Web Tokens (JWT) ...
  5. Basic authentication.
Oct 25, 2023

What can I use instead of API key authentication? ›

Alternative authentication methods like OAuth, JWT, and HMAC-based API keys can offer increased security. The choice of method depends on the type of API and the required security level.

When to use API keys? ›

Some common use cases for API keys include:
  1. Security API keys can offer an extra layer of security for an API, better locking down data shared between API and client.
  2. Access control With API keys, developers can make sure only authorized users have access to data or resources provided by an API.
May 22, 2023

Which is better, JWT or OAuth? ›

JWT is suitable for stateless applications, as it allows the application to authenticate users and authorize access to resources without maintaining a session state on the server. OAuth, on the other hand, maintains a session state on the server and uses a unique token to grant access to the user's resources.

What is more secure than JWT? ›

Secure: Opaque tokens do not contain any user information, making them more secure than JWT tokens. Flexible: Opaque tokens can be customized to store additional user information in the authorization server, which can be retrieved by the resource server when needed.

What is the alternative to JWT authentication? ›

OAuth2, Passport, Spring Security, JavaScript, and Git are the most popular alternatives and competitors to JSON Web Token. Powerful collaboration, review, and code management for open ... Powerful collaboration, review, and code management for open ...

When to use OAuth vs API key? ›

API keys are good for read-only data, but not as good for authorization. OAuth tokens are better for authorization, but can be more complex to implement. The best way to secure a REST API depends on the specific needs of the application.

Why do we use API key? ›

An application programming interface (API) key is a code used to identify and authenticate an application or user. API keys are available through platforms, such as a white-labeled internal marketplace. They also act as a unique identifier and provide a secret token for authentication purposes.

What is one benefit that OAuth provides over an API key approach? ›

OAuth is the answer to accessing user data with APIs. Unlike with API keys, OAuth does not require a user to go spelunking through a developer portal. In fact, in the best cases, users simply click a button to allow an application to access their accounts.

Why use JWT instead of session? ›

Choosing between JWT and session-based authentication depends on your application's specific needs. If you prioritize statelessness and scalability, JWT might be your go-to. For traditional applications where immediate control over sessions is crucial, session-based authentication holds the upper hand.

Top Articles
Google Pay | UOB Singapore
How to invest in AI’s next phase | J.P. Morgan Private Bank U.S.
Faridpur Govt. Girls' High School, Faridpur Test Examination—2023; English : Paper II
Crossed Eyes (Strabismus): Symptoms, Causes, and Diagnosis
Comcast Xfinity Outage in Kipton, Ohio
Plus Portals Stscg
Flights to Miami (MIA)
Imbigswoo
Weekly Math Review Q4 3
Cvs Learnet Modules
Winterset Rants And Raves
อพาร์ทเมนต์ 2 ห้องนอนในเกาะโคเปนเฮเกน
Cnnfn.com Markets
10 Free Employee Handbook Templates in Word & ClickUp
Echo & the Bunnymen - Lips Like Sugar Lyrics
2015 Honda Fit EX-L for sale - Seattle, WA - craigslist
Craigslist Malone New York
How Much Are Tb Tests At Cvs
Puretalkusa.com/Amac
Craighead County Sheriff's Department
Adam4Adam Discount Codes
Praew Phat
1-833-955-4522
Spider-Man: Across The Spider-Verse Showtimes Near Marcus Bay Park Cinema
Kp Nurse Scholars
Ibukunore
Crawlers List Chicago
Drift Boss 911
Glover Park Community Garden
Brbl Barber Shop
Dewalt vs Milwaukee: Comparing Top Power Tool Brands - EXTOL
Wics News Springfield Il
Makemv Splunk
Milwaukee Nickname Crossword Clue
Cable Cove Whale Watching
Craigslist Boerne Tx
24 Hour Drive Thru Car Wash Near Me
Cheap Motorcycles Craigslist
Umiami Sorority Rankings
Ishow Speed Dick Leak
Puretalkusa.com/Amac
Live Delta Flight Status - FlightAware
Jetblue 1919
Lamont Mortuary Globe Az
'The Nun II' Ending Explained: Does the Immortal Valak Die This Time?
All Weapon Perks and Status Effects - Conan Exiles | Game...
Rise Meadville Reviews
Access to Delta Websites for Retirees
5103 Liberty Ave, North Bergen, NJ 07047 - MLS 240018284 - Coldwell Banker
Upcoming Live Online Auctions - Online Hunting Auctions
How Did Natalie Earnheart Lose Weight
All Obituaries | Roberts Funeral Home | Logan OH funeral home and cremation
Latest Posts
Article information

Author: The Hon. Margery Christiansen

Last Updated:

Views: 5977

Rating: 5 / 5 (50 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: The Hon. Margery Christiansen

Birthday: 2000-07-07

Address: 5050 Breitenberg Knoll, New Robert, MI 45409

Phone: +2556892639372

Job: Investor Mining Engineer

Hobby: Sketching, Cosplaying, Glassblowing, Genealogy, Crocheting, Archery, Skateboarding

Introduction: My name is The Hon. Margery Christiansen, I am a bright, adorable, precious, inexpensive, gorgeous, comfortable, happy person who loves writing and wants to share my knowledge and understanding with you.