Smart GeekSmart Geek
HomeArticlesCategories
Smart Geek

Thoughtful articles on technology, design, and culture in multiple languages.

Navigation

  • Home
  • Articles
  • Categories
  • About
  • Contact
  • Privacy Policy
  • RSS Feed

© 2026 Smart Geek. All rights reserved.

BlogProgrammingAPI Authentication Methods Explained
Programming

API Authentication Methods Explained

The first time I called a real API with a live key in my JavaScript code, I pushed it straight to GitHub and within four hours, someone else's server was running charges on my account. Authentication isn't just a technical box to tick. It's the difference between a working project and a security disaster waiting to happen.

Sayed Bin FahadSayed Bin Fahad
July 16, 202614 min read58 views
api authentication methods explainedapi key vs oauth vs jwthow api authentication worksrest api authentication 2026secure api authentication beginner guideapplication programming interface

The first time I called a real API with a live key in my JavaScript code, I pushed it straight to GitHub and within four hours, someone else's server was running charges on my account. Authentication isn't just a technical box to tick. It's the difference between a working project and a security disaster waiting to happen.


What Is API Authentication and Why Does It Matter?

API authentication is the process of verifying the identity of a client like a web app, mobile app, or backend service, before allowing it to access protected resources or perform actions through an API. Without authentication, any person or bot on the internet could read your users' data, post on their behalf, or drain your API credits in minutes.

Authentication answers the question: "Who is making this request?" It's the first gate every secure API enforces, and understanding how it works is non-negotiable for any developer building real applications.


What Is an API Key and How Does It Work?

An API key is a long, randomly generated string that acts as a simple password for your application. When you register for an API service like a weather API, a maps API, or an AI service. The provider generates a unique key tied to your account. You include that key in every request you send, and the server checks it against its database to confirm who you are before returning data.

API keys are typically sent in one of three places: as a query parameter in the URL, in a custom request header, or in the Authorization header.

Sending an API key in a Fetch request:

//javascript
const API_KEY = process.env.MY_API_KEY; // Never hardcode this

async function getWeatherData(city) {
  try {
    const response = await fetch(
      `https://api.weatherexample.com/current?city=${city}`,
      {
        headers: {
          'X-API-Key': API_KEY
        }
      }
    );

    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }

    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Request failed:', error);
  }
}

getWeatherData('Dhaka');

When to use API keys: Simple server-to-server communication, internal tooling, quick prototypes, and third-party services where you're the only client. They're fast to implement but offer limited security on their own. A leaked key gives anyone full access until you revoke it.

Pros: Easy to implement, easy to understand, no expiry by default. Cons: No built-in expiry, easily leaked if mishandled, no user-level access control.


Rest API or GraphQL API


What Is Basic Authentication and Why Is It Mostly Outdated?

Basic Authentication is a simple HTTP authentication scheme where the client sends a username and password encoded in Base64 inside the Authorization header with every request. The header looks like: Authorization: Basic dXNlcjpwYXNzd29yZA==, where the encoded part is just username:password in Base64, which is trivially reversible, not encrypted.

Sending Basic Auth in a Fetch request:

//javascript
async function fetchWithBasicAuth() {
  const username = 'myuser';
  const password = 'mypassword';
  const credentials = btoa(`${username}:${password}`); // Base64 encode

  try {
    const response = await fetch('https://api.example.com/data', {
      headers: {
        'Authorization': `Basic ${credentials}`
      }
    });

    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }

    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Request failed:', error);
  }
}

fetchWithBasicAuth();

Why is Basic Auth mostly outdated? Because it sends credentials with every single request, Base64 encoding is not encryption. Anyone intercepting traffic over plain HTTP can decode the header instantly. It's only acceptable over HTTPS (where the transport layer encrypts it), and even then, it's been largely replaced by token-based methods. You'll still encounter Basic Auth in legacy APIs and some internal tools, but you should avoid it for any new project.


What Are Bearer Tokens and How Do They Differ from API Keys?

A Bearer Token is a security token included in the Authorization header with the prefix Bearer, indicating that whoever "bears" (holds) this token is granted access. The core difference from an API key is that bearer tokens are usually temporary. They expire after a set period and they're issued dynamically after a successful login or authentication flow rather than being statically assigned.

Bearer tokens are the delivery mechanism; they're how you send the token to the server. JWT and OAuth access tokens are both commonly sent as Bearer Tokens.

Sending a Bearer Token in a Fetch request:

//javascript
async function fetchUserProfile(accessToken) {
  try {
    const response = await fetch('https://api.example.com/user/profile', {
      headers: {
        'Authorization': `Bearer ${accessToken}`
      }
    });

    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }

    const profile = await response.json();
    console.log(profile);
  } catch (error) {
    console.error('Failed to fetch profile:', error);
  }
}

// accessToken would come from your auth flow, not hardcoded
fetchUserProfile('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...');

Bearer tokens are the standard format for authenticated API requests in modern applications. You'll use this pattern constantly once you start working with JWTs or OAuth.


What Is a JWT and How Is It Structured?

A JWT (JSON Web Token) is a compact, self-contained token that encodes a set of claims like a user's ID, role, and token expiry directly inside the token itself. Unlike API keys that require a database lookup to validate, JWTs can be verified by the server using a cryptographic signature without any database query at all, which makes them fast and scalable.

Every JWT has exactly three parts separated by dots: Header.Payload.Signature.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjQyLCJyb2xlIjoiYWRtaW4iLCJleHAiOjE3MjAwMDAwMDB9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Decoded, those three parts look like:

Header, specifies the algorithm used to sign the token:

json

{
  "alg": "HS256",
  "typ": "JWT"
}

Payload, contains the actual claims (user data and expiry):

json

{
  "userId": 42,
  "role": "admin",
  "exp": 1720000000
}

Signature, a cryptographic hash of the header and payload, signed with a secret key only your server knows:

HMACSHA256(
  base64UrlEncode(header) + "." + base64UrlEncode(payload),
  your-secret-key
)

The server verifies the signature on every request. If the token was tampered with, the signature won't match and the request is rejected. JWTs are sent as Bearer Tokens and are the most common authentication method for custom-built REST APIs.

When to use JWT: Building your own backend API with user login, session management without server-side storage, and microservices that need to verify identity across services.


What Is OAuth 2.0 and How Does the Authorization Flow Work?

OAuth 2.0 is an authorization framework, not just an authentication method. It allows users to grant third-party applications limited access to their accounts on another service, without sharing their password. It's the technology behind every "Login with Google," "Continue with GitHub," and "Connect with Spotify" button you've ever clicked.

The most common flow is the Authorization Code Flow, which works like this:

  1. Your app redirects the user to the OAuth provider (e.g., Google's login page) with a request for specific permissions (scopes).

  2. The user logs in and approves the requested permissions on Google's own interface. Your app never sees their password.

  3. Google redirects the user back to your app with a short-lived authorization code in the URL.

  4. Your backend exchanges that code (plus your app's secret) for an access token and optionally a refresh token.

  5. You use the access token as a Bearer Token to make API calls on behalf of the user.

//javascript
// Step 3: Your callback route receives the authorization code
// Step 4: Exchange the code for an access token (done on the backend)

async function exchangeCodeForToken(authorizationCode) {
  try {
    const response = await fetch('https://oauth2.googleapis.com/token', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: new URLSearchParams({
        code: authorizationCode,
        client_id: process.env.GOOGLE_CLIENT_ID,
        client_secret: process.env.GOOGLE_CLIENT_SECRET,
        redirect_uri: 'https://yourapp.com/auth/callback',
        grant_type: 'authorization_code'
      })
    });

    if (!response.ok) {
      throw new Error(`Token exchange failed: ${response.status}`);
    }

    const tokens = await response.json();
    // tokens.access_token is now usable as a Bearer Token
    console.log('Access token received:', tokens.access_token);
  } catch (error) {
    console.error('OAuth exchange error:', error);
  }
}

When to use OAuth 2.0: Any time you need users to log in via an existing provider (Google, GitHub, Facebook), access another service's API on behalf of your users, or implement social login without managing passwords yourself.


How Do All Five Methods Compare?

Method

Security Level

Best For

Complexity

Stateless?

API Key

Low–Medium

Server-to-server, third-party services

Very Low

Yes

Basic Auth

Low

Legacy systems only (over HTTPS only)

Very Low

Yes

Bearer Token

Medium–High

Sending any token type to an API

Low

Yes

JWT

High

Custom backends, user sessions, microservices

Medium

Yes

OAuth 2.0

Very High

Third-party login, delegated access

High

Partially

Stateless means the server doesn't need to store session data. It validates every request independently. JWTs are fully stateless because all the data is in the token itself. OAuth 2.0 is partially stateless because the access tokens are stateless, but the authorization server maintains state about issued tokens.


Which Authentication Method Should You Choose?

The right method depends on what you're building, not which sounds most impressive. Here's a direct decision guide:

Use API Keys when you're calling a third-party service from your own backend (weather APIs, mapping APIs, AI APIs), building internal tools with controlled access, or prototyping something quickly. Keep the key on the server side, never in frontend code.

Use JWT when you're building your own backend with user login, want stateless authentication without server-side session storage, or are connecting multiple microservices that need to trust a shared user identity.

Use OAuth 2.0 when you need "Login with Google/GitHub/Facebook" functionality, need to access another service's API on behalf of your users, or want to avoid managing passwords entirely. For most consumer apps with social login, OAuth is the right choice.

Use Basic Auth only as a last resort for legacy API compatibility over HTTPS and never for new projects.

Use Bearer Token as the delivery format for your JWT or OAuth access token. It's not a method in isolation, it's how you send the token in headers.


How Do You Store API Keys and Tokens Safely?

Never store API keys or tokens directly in your frontend JavaScript files. Any key visible in your browser's source code or network requests is exposed to anyone who opens DevTools and bots do look.

The correct approach depends on your environment:

  • Backend (Node.js, Python, etc.): Use environment variables and .env files. Load them with a library like dotenv and access them as process.env.MY_API_KEY. Never commit .env files to version control add .env to your .gitignore immediately when you create it.

  • Frontend (React, Vue, plain JS): Keys that belong on the server should never reach the frontend. Route requests through your own backend endpoint that injects the key server-side before calling the third-party API.

  • Tokens (JWT, OAuth access tokens): Store in memory (a JavaScript variable) for maximum security, or in httpOnly cookies that JavaScript can't access. Avoid localStorage for sensitive tokens, see the mistakes section below.

⚠️ Never Push API Keys to GitHub Automated bots scan every public GitHub commit within minutes of it being pushed, actively hunting for API keys, tokens, and credentials. If your key appears in a commit even if you delete it in the next commit. It is considered compromised and should be revoked and rotated immediately. The git history still contains it. Set up a .gitignore before your first commit, not after you've already pushed. Services like GitGuardian and GitHub's own secret scanning will alert you, but the key is already exposed by the time the alert arrives.

Use fetch API in javascript


What Are the Most Common API Authentication Mistakes Developers Make?

Why Is Storing Tokens in localStorage Dangerous?

Storing JWT or OAuth tokens in localStorage exposes them to Cross-Site Scripting (XSS) attacks. Any malicious JavaScript injected into your page through a compromised third-party script, an ad network, or an XSS vulnerability can read everything in localStorage and steal your tokens instantly. Use httpOnly cookies instead, which are inaccessible to JavaScript by design.

Why Does Not Setting Token Expiry Create a Security Risk?

A JWT or access token without an expiry (exp claim) is valid forever. If it's stolen, the attacker has permanent access until you manually rotate keys or invalidate tokens. Always set a short expiry (15 minutes to a few hours for access tokens) and use refresh tokens for longer sessions. A slightly worse user experience from re-authentication is far better than permanent account compromise.

Why Should You Never Use Basic Auth Over Plain HTTP?

Basic Auth encodes credentials in Base64, which is trivially reversible. It's not encryption. Sending Basic Auth over plain HTTP exposes your username and password in plain text to anyone monitoring network traffic between the client and server. Basic Auth is only acceptable over HTTPS, where the TLS layer encrypts the entire request including headers.

What Is the Difference Between Authentication and Authorization?

Authentication and authorization are separate concepts that are easy to confuse. Authentication verifies who you are "prove you are user #42." Authorization determines what you're allowed to do "user #42 can read posts but cannot delete them." Most authentication methods (JWT, OAuth) include role or permission claims to handle both, but they are logically distinct steps. Getting this wrong leads to bugs where authenticated users can access resources they shouldn't.


FAQ

What Is the Difference Between Authentication and Authorization?

Authentication is the process of verifying identity, confirming that a request comes from who it claims to be. Authorization is the process of verifying permissions and confirming that the verified identity is allowed to perform a specific action or access specific data. Authentication always comes first. A user can be authenticated (logged in) but still unauthorized to access a specific resource (like an admin-only endpoint).

Is JWT the Same as OAuth?

No, JWT and OAuth are different things that are often used together. OAuth 2.0 is an authorization framework that defines how to obtain access. JWT is a token format that OAuth (and many other systems) use to represent that access. OAuth access tokens are often formatted as JWTs, but OAuth can also use opaque tokens. You can use JWTs completely independently of OAuth in your own authentication system.

How Long Should a JWT Token Last?

Access JWTs should typically last 15 minutes to 1 hour for most applications. Short-lived tokens limit the damage window if a token is stolen. Once expired, it's useless. Pair short-lived access tokens with a longer-lived refresh token (7–30 days) that can issue new access tokens silently, so users aren't constantly asked to log in. For sensitive financial or medical applications, even shorter access token windows (5–15 minutes) are appropriate.

What Happens If an API Key Is Leaked?

Revoke and rotate the key immediately through the API provider's dashboard don't wait. Leaked API keys can be used to consume your credits, access your data, or impersonate your application. After revoking, audit your API usage logs to see if unauthorized calls were made. Then audit your codebase and git history to find and remove every instance of the exposed key, add .env to .gitignore, and generate a new key to replace it.

Can You Use Multiple Authentication Methods Together?

Yes, and many real-world applications do. A common pattern is using OAuth 2.0 for user-facing login (so users authenticate with Google or GitHub) while using API keys for server-to-server calls to third-party services all within the same application. Some APIs also accept both API keys and Bearer Tokens depending on the endpoint. The key is to use the right method for each specific use case rather than forcing one method to cover everything.


Wrapping Up

API authentication is one of those topics where a single afternoon of focused reading pays off across every project you build afterward the patterns are consistent whether you're calling a weather API, building a login system, or integrating social auth. Start with API keys for simplicity, reach for JWT when you need your own user authentication, and layer in OAuth when your users need to log in with existing accounts.

Sayed Bin Fahad

Sayed Bin Fahad

Contents

  • What Is API Authentication and Why Does It Matter?
  • What Is an API Key and How Does It Work?
  • What Is Basic Authentication and Why Is It Mostly Outdated?
  • What Are Bearer Tokens and How Do They Differ from API Keys?
  • What Is a JWT and How Is It Structured?
  • What Is OAuth 2.0 and How Does the Authorization Flow Work?
  • How Do All Five Methods Compare?
  • Which Authentication Method Should You Choose?
  • How Do You Store API Keys and Tokens Safely?
  • What Are the Most Common API Authentication Mistakes Developers Make?
  • Why Is Storing Tokens in localStorage Dangerous?
  • Why Does Not Setting Token Expiry Create a Security Risk?
  • Why Should You Never Use Basic Auth Over Plain HTTP?
  • What Is the Difference Between Authentication and Authorization?
  • FAQ
  • What Is the Difference Between Authentication and Authorization?
  • Is JWT the Same as OAuth?
  • How Long Should a JWT Token Last?
  • What Happens If an API Key Is Leaked?
  • Can You Use Multiple Authentication Methods Together?
  • Wrapping Up

Tags

Programming

Related Articles

Fix 'MySQL Shutdown Unexpectedly' in XAMPP
Programming

Fix 'MySQL Shutdown Unexpectedly' in XAMPP

Fix the frustrating “MySQL Shutdown Unexpectedly” error in XAMPP with this clear, step-by-step guide. Learn the most common causes from port conflicts to corrupted data files and follow simple solutions to get your local server running smoothly again in minutes.

mysqlxamppphp
Sayed Bin Fahad
Apr 9, 2026 5 min
How to Install Python on Windows 11
Programming

How to Install Python on Windows 11

Learn how to install Python on Windows 11 step-by-step. Covers download, PATH setup, version check, and common errors. Updated May 2026 for beginners.

pythonwindows 11install python
Sayed Bin Fahad
May 3, 2026 9 min
Programming

Python vs JavaScript: Which Should You Learn First?

You've decided to finally learn programming, and now you're stuck on the first decision that feels way bigger than it should Python or JavaScript? I've watched dozens of beginners freeze at this exact crossroads, so let's settle it with facts instead of hype.

javascriptpythonweb
Sayed Bin Fahad
Jun 18, 2026 8 min