An Overview of Basic, JWT, API Key, and OAuth Authentication Techniques


In the world of distributed systems and modern APIs, authentication plays a critical role in securing resources and validating users. Choosing the right authentication method depends on use cases, system architecture, and security requirements. This blog explores five popular authentication methods: Basic Authentication, JWT (JSON Web Tokens), API Keys, and OAuth, along with their use cases, pros, and cons.
1. Basic Authentication
Overview
Basic Authentication is a simple way to verify users in REST APIs by sending a username and password in HTTP headers. It’s easy to use but less secure, especially without HTTPS, making it unsuitable for sensitive data or production use.
Here's a quick summary of Basic Authentication in REST APIs:
Client Request: The client sends a request to the server with authentication details in the request headers.
Encoding: Username and password are combined as
username:password
and base64-encoded. Note: This is not encryption.Header: The encoded credentials are added to the HTTP request header like this:
Authorization: Basic base64(username:password)
Server Check: The server decodes the header, retrieves the username and password, and verifies them.
Response: If valid, the server processes the request. If not, it returns a 401 Unauthorized error.
It’s important to use HTTPS when implementing Basic Authentication to encrypt the communication between the client and the server. The credentials are sent in plain text without encryption, making it vulnerable to threats.
Use Cases
Legacy systems or internal applications.
Simple APIs with low security concerns.
Pros
Simple to implement and use.
Supported by all major HTTP clients and browsers.
Cons
Credentials are sent with every request, increasing exposure risk.
Base64 encoding is not encryption so increasing security risk. Needs TLS for security.
No session management—every request re-sends credentials.
Real-Life Example
- Accessing internal tools or staging environments using a browser pop-up prompt.
2. Token Based Authentication
Overview
Token authentication is more secure than basic authentication since it involves using a unique token generated for each user. JSON Web Tokens (JWT) is a popular token-based authentication method.
JWTs are self-contained and can store user information, reducing the need for constant database queries. This token is sent with each request to authenticate the user. Token authentication is also a good choice for applications requiring frequent authentication, such as single-page or mobile applications.
Since the authentication process does not require user passwords in each request, once a user enters the credentials, receive a unique encrypted token valid for a specified session time.it is more efficient and can handle more concurrent requests.
JWT (JSON Web Token) authentication works in a client-server interaction:
1. User Login
The client sends login credentials (username and password) to the server.
The server verifies the credentials.
2. Token Generation
Upon successful authentication, the server generates a JWT.
The token contains:
Header: Specifies the token type (
JWT
) and signing algorithm.Payload: Contains user data (e.g., user ID) and claims.
Signature: Ensures the token’s integrity using a secret key.
In a serialised form, JWT represents a string in the following format:
[header].[payload].[signature]
Actual JWT token looks like
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTIzNDU2Nzg5LCJuYW1lIjoiSm9zZXBoIn0.OpOSSw7e485LOP5PrzScxHb7SR6sAOMRckfFwi4rp7o
In deserialised form, JWT will be as per below:
{
"header": { "alg": "HS256", "typ": "JWT" },
"payload": { "sub": "1234567890", "name": "John Doe", "admin": true },
"signature": "signed-data"
}
3. Token Delivery
- The server sends the JWT to the client (often in the response body or a cookie).
4. Token Usage
The client includes the JWT in the
Authorization
header (e.g.,Bearer <token>
) of subsequent requests.The token serves as proof of authentication.
Request Header has below:
Authorization: Bearer <token>
5. Token Validation
The server validates the JWT by:
Verifying the signature.
Checking the token’s expiration and claims.
6. Access Granted
If the token is valid, the server processes the request and returns the response.
If invalid, the server denies access, often returning a
401 Unauthorized
status.
Key Points:
JWTs are stateless, meaning the server doesn’t store session information.
Expired or invalid tokens require re-authentication.
Tokens can include additional claims for granular access control.
Use Cases
Short-lived API sessions.
Microservices communication.
Stateless authentication for web and mobile applications.
Single Sign-On (SSO) scenarios.
Pros
Self-contained and can carry user claims.
Stateless: No need to query the database after token issuance.
Supports token expiration and custom claims.
Cons
Larger token size compared to others.
If not properly invalidated, compromised tokens remain valid until expiry.
Need secure storage to avoid leakage.
Real-Life Example
- Accessing APIs in cloud platforms (e.g., AWS, Azure) and microservice architecture.
3. API Key Authentication
Overview
API keys are unique strings assigned to each client, included in requests to identify the client. They can be passed via headers, query parameters, or request bodies.
Obtaining API Key: Clients request an API key from the API provider. This is usually done through a developer portal or some registration process.
Including API Key in Requests: Once the API key is obtained, it must be included in each API request.
GET /api/resource?api_key=123abc
Server-Side Validation: The API server receives the request and extracts the API key from the specified location (URL parameter, header, etc.). The server checks the validity of the API key by comparing it against a list of authorized keys stored in its database.
Authorization Check: Once the API key is validated, the server checks if the associated client or application has the necessary permissions to perform the requested action.
While API keys are a straightforward authentication method, they have some limitations. One of the main concerns is that API keys can be exposed easily if not handled securely, leading to potential security risks. Therefore, following best practices, such as using HTTPS, avoiding exposure of keys in client-side code, and implementing proper critical management practices, is essential. Other authentication methods, like token-based authentication (JWTs), may be preferred for more sensitive applications.
Use Cases
Public APIs with limited scope access.
Service-to-service communication.
Pros
Simple and easy to use.
Can be restricted by IP or referrer for added security.
Cons
No built-in user identity (just a key).
Vulnerable to theft if exposed in public repositories or URLs.
Hard to revoke individual keys unless tracked explicitly.
Real-Life Example
- APIs for weather, currency conversion, or third-party integration services.
5. OAuth 2.0
Overview
Applications often need to interact with each other on behalf of users. Whether it’s granting access to your Google account for a new app or allowing a third-party service to post to your social media, OAuth 2.0 has become the go-to solution for secure, seamless access delegation.
In this blog, we’ll explore the core concepts of OAuth 2.0, why it’s essential, and how it enables secure interactions between applications.
What is OAuth 2.0?
OAuth 2.0 (Open Authorization 2.0) is an open standard protocol designed to provide secure authorization for applications without exposing user credentials. It allows users to grant limited access to third-party application.
For example, when you sign in to an app using your Google account, OAuth 2.0 facilitates the process, ensuring the app gets access to your profile details without revealing your password.
Key Concepts in OAuth 2.0
OAuth 2.0 operates through several key roles:
Resource Owner (User): The individual who owns the data and can grant access to it.
Client (Application): The app requesting access to the user’s data.
Authorization Server: The server that authenticates the user and grants tokens.
Resource Server: The server that holds the user’s data and validates tokens for access.
Token-Based Access
OAuth 2.0 uses tokens instead of credentials to grant access. These tokens are temporary and can be tailored for specific permissions, making them more secure and flexible.
There are roughly 2 types of token:
Access Token: Used to access protected resources.
Refresh Token: Used to obtain a new access token when the current one expires.
Common OAuth 2.0 Grant Flows
Authorization Code Flow (most secure, used for server-side applications):
Authorization Request: The client redirects the user to the authorization server to log in and approve access.
Authorization Grant: The authorization server provides an authorization code.
Token Request: The client exchanges the authorization code for an access token by making a back-channel request.
Resource Request: The client uses the access token to access the protected resource.
User request for login and authenticate to get auth code
https://localhost:8080/realms/myrealm/protocol/openid-connect/auth
?response_type=code &client_id=myclient &redirect_uri=
http://localhost:3000/callback
&scope=openid
After successful authentication, auth server redirect the user to the redirect uri with authorization code
http://localhost:3000/callback?code=AUTHORIZATION_CODE
Once we get authorization code from the url
One can do below curl to get token
curl -X POST "
http://localhost:8080/realms/myrealm/protocol/openid-connect/token
" -H "Content-Type: application/x-www-form-urlencoded" -d "grant_type=authorization_code" -d "client_id=myclient" -d "client_secret=mysecret" -d "redirect_uri=
http://localhost:3000/callback
" -d "code=AUTHORIZATION_CODE"
Response
{ "access_token": "eyJhbGciOiJSUzI1NiIsInR5c...", "expires_in": 300, "refresh_token": "eyJhbGciOiJIUzI1NiIs...", "id_token": "eyJhbGciOiJSUzI1NiIsInR5c...", "token_type": "Bearer" }
- Implicit Flow - deprecated (used for single-page applications):
- The client directly receives the access token without an authorization code exchange.
- Client Credentials Flow (used for machine-to-machine communication):
The client authenticates itself to the authorization server and directly obtains an access token.
It doesn’t require any callback url and auth code exchange. Authorization code flow requires callback url. Auth server returns JWT token.
User will pass clientId and client secret for authentication server.
curl -X POST "
https://auth.example.com/oauth/token
" -H "Content-Type: application/x-www-form-urlencoded" -d "client_id=myclient" -d "client_secret=mysecret" -d "grant_type=client_credentials"
Response
{ "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI...", "expires_in": 300, "token_type": "Bearer" }
It doesn’t provide refresh token in cc flow.
- Resource Owner Password Credentials Flow (discouraged due to security concerns):
- The client directly collects the user’s credentials and exchanges them for an access token.
Common OAuth 2.0 Use Cases
Social Media Integration: Allowing apps to post on behalf of users.
Cloud Storage Access: Enabling apps to fetch files from services like Google Drive or Dropbox.
Payment Gateways: Granting access to payment platforms without sharing sensitive information.
Real life : A Step-by-Step Example
Let’s say you want to use a third-party app to analyze your Gmail data:
Authorization Request: The app redirects you to Google’s authorization server.
User Consent: You log in and grant permission.
Token Issuance: Google provides an access token to the app.
Data Access: The app uses the token to fetch your Gmail data securely.
Pros
Securely avoids sharing user credentials with third-party apps.
Supports Single Sign-On (SSO) for seamless user experience.
Provides granular access control through token scopes.
Offers token expiration and refresh for enhanced security.
Flexible for diverse use cases (e.g., mobile, web, API).
Widely adopted and integrated with major platforms.
Cons
Complex implementation increases the risk of errors.
Token storage and management require careful handling.
Implicit flow deprecation impacts older implementations.
Reliance on third-party providers may raise privacy concerns.
Choosing the Right Authentication Method
Authentication | Best for | Security | Ease of Implementation |
Basic | Simple apps | Low | High |
JWT | SPAs, SSO | High | Moderate |
API Key | Public APIs | Low | High |
OAuth 2.0 | Third-party access | Very High | Low |
Conclusion
Each authentication method has its own strengths and trade-offs. For simple use cases, API Keys or Basic Auth may suffice. For stateless, scalable systems, JWT is a strong choice. For delegated access and federated identity, OAuth 2.0 is a robust option. Evaluate your security needs and system architecture before choosing the most appropriate solution.
Have any questions or insights about these methods? Let’s discuss in the comments! 👇
Subscribe to my newsletter
Read articles from Anish Ratnawat directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
