DEV Community

Cover image for API security: API authentication algorithm for beginners
Usman Zahid
Usman Zahid

Posted on

API security: API authentication algorithm for beginners

When building APIs, securing user access is critical. One of the simplest yet effective methods is token-based authentication. Let’s walk through a beginner-friendly approach used by many modern systems.


The Idea: Personal Access Tokens (PATs)

Instead of passing around usernames and passwords with every request, we issue tokens. These tokens act like digital keys: short strings that the client can store and send with each API call.

A safe way to implement this is to split a token into two parts:

  1. Token ID – a short identifier that lets us quickly look up the token in the database.
  2. Secret Value – a long random string that is never stored in plain text. Instead, we only keep its hash in the database.

The user only sees the full token once at creation. After that, only the hashed value exists on the server side.


How It Works

  1. Token Creation

    • Server generates a random secret string.
    • Hash this string (e.g., SHA-256) and save it with the Token ID in the database.
    • Give the user a full token in the format:
     <token_id>|<secret>
    
  2. Token Storage (Client Side)

    • The client is responsible for securely storing the token.
    • If it’s lost, it cannot be recovered since the server only stores the hash.
  3. Authentication (Request Flow)

    • User sends the token with their API request.
    • The server splits it into token_id and secret.
    • Look up the token by token_id in the database.
    • Hash the provided secret and compare it with the stored hash.
    • If they match, the request is authenticated.

Why This Is Secure

  • No plain secrets in the database: Even if the database leaks, attackers only see hashes.
  • Quick lookups: The token_id lets you jump straight to the correct row instead of scanning entire tables.
  • Revocation: Tokens can be individually revoked by deleting them from the database.
  • Granularity: Different tokens can have different scopes or permissions.

Takeaway

This approach is simple to implement, language-agnostic, and far safer than storing raw tokens. It’s a solid starting point for anyone designing token-based authentication in APIs.

Usman Zahid

Top comments (0)