Token-Based Authentication Guide

This guide will provide an in-depth understanding of token-based authentication, covering its fundamentals, best practices, and everything you need to know for a successful implementation.

March 10, 20259 min read

Token-Based Authentication Guide

Introduction

Authentication is one of the ways of securing your applications (the communication between the client and server) and one effective method is token-based authentication, which ensures users can securely access protected resources

This guide explains how token authentication works, focusing on JWT (JSON Web Tokens) and best security practices.

Try Kodaschool for free

Click below to sign up and get access to free web, android and iOs challenges.

Sign Up

What is Token-Based Authentication?

This is a method where users authenticate once and receive a token, which is then sent with every request to verify identity. Unlike session-based authentication, which relies on storing session data on the server, tokens allow for stateless authentication, improving scalability and efficiency.

Common Authentication Methods:

There are different kind of authentication methods, which are:

  • Token-Based Authentication (JWT)
  • OAuth2 - Single Sign-On via third parties like Google, Microsoft, etc.
  • Session-Based Authentication - Server-managed sessions
  • Certificate-Based Authentication - Hardware devices like YubiKeys, smart cards

Authentication Flow

  1. User submits login credentials (email & password) on the client side, by filling in a form.
  2. The client sends it to the server, which is then validated and generates a JWT and is then sent back to the client.
  3. Client stores the generated token securely (e.g., in memory or HTTP-only cookies).
  4. Client sends the token in the request header for protected routes.

Server verifies the token before processing the request.

Image

The JWT standard

One of the widely used methods for securing API authentication. They provide a stateless way of authenticating users, allowing applications to verify identity without storing session data on the server.

What is JWT?

A JSON Web Token (JWT) is a compact, URL-safe token format that encodes JSON objects to form a secure way in which data is transferred through two parties. It mainly consists of three parts:

  1. Header - Specifies token type and signing algorithm that is used.
  2. Payload - Contains claims (usually data about the user or entity). like user ID, role, and expiration time.
  3. Signature - Ensures token integrity using a secret key. A signature is created using the algorithm specified in the header to sign a combination of the encoded header, the encoded payload and a secret. The secret helps us verify that the token hasn’t been tampered with and should be kept somewhere safe (you can use env variables)

NOTE: You should not always include sensitive data in the payload, since it isn't secured by default unless there is additional encryption.

Here is a sample jwt you check it out:

Image

Example JWT:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Authentication flow: in-depth explanation

Step 1: User Signup

On the client:

  • Collect user details using a form.
  • Validate and sanitize input (e.g., check email format, ensure fields aren’t empty, enforce strong passwords).
  • Package the data into a JSON object and send it to the signup endpoint.

On the backend:

  • Validate and sanitize the received data.
  • Hash and salt the password using a library like bcrypt (never store passwords in plain text).
  • Check for duplicate users (if needed) and save the user details in the database.

NB: Enhance the authentication flow by redirecting users directly to the app after signup instead of the login page. Since we already have the user’s credentials, we can issue an access token upon signup, just like during login.

Step 2: User Login

On the client:

  • Collect user credentials and validate input (e.g., check email format, ensure fields aren’t empty).
  • Package the data into a JSON object and send it to the login endpoint.

On the backend:

  • Verify the user exists in the database.
  • Compare the stored hashed password with the one provided by the user.

Step 3: Token Generation

Using a JWT library, generate two tokens:

  1. Access Token:
    • Short-lived (expires in minutes or hours).
    • Contains essential data like user ID, roles, and permissions.
  2. Refresh Token:
    • Long-lived (expires in days or months).
    • Used to generate new access tokens when the current one expires.

Step 4: Storing Tokens

Access Token:

  • Sent back to the client as a JSON response.
  • Stored in memory using state, context, or variables (e.g., in React).
  • Used in the Authorization header for all protected requests.

NB: Avoid storing access tokens in local storage due to XSS risks. Keeping them in memory is safer unless the application has JavaScript injection vulnerabilities.

Refresh Token:

  • Stored securely in an HTTP-only cookie (inaccessible to JavaScript).
  • Automatically included in requests to the server.
  • Helps mitigate XSS attacks and, with proper security settings, can prevent CSRF attacks.

NB: Configuring SameSite cookies or CSRF tokens can further enhance your security.

Token differences

  • An Access Token is primarily used for authenticating requests. It is short-lived, typically lasting from a few minutes to several hours. With every request, the access token is sent in the Authorization header to verify the user's identity and permissions. Since it expires quickly, it has a lower security risk. Access tokens generally contain data such as the user ID, roles, and permissions and are usually kept in memory or application state for security reasons.
  • On the other hand, a Refresh Token is used to generate new access tokens when the current one expires. It has a much longer lifespan, lasting from days to months, and is used only at a specific endpoint dedicated to refreshing tokens. Unlike access tokens, refresh tokens are typically stored in an HTTP-only cookie for added security. They contain minimal information, such as the user ID or token ID, but pose a higher security risk if exposed, as they can be used to obtain new access tokens.

Step 5: Using Tokens

Access Token Flow:

  • The client includes the access token in the Authorization header of each request.
  • The server verifies the token, checks its expiry, decodes it, validates permissions, and then processes the request.

Refresh Token Flow:

  • When the access token expires, the client requests a new one using the refresh token.
  • The server retrieves the refresh token from the HTTP-only cookie, verifies it, and issues a new access token.
  • Optionally, the old refresh token can be blacklisted to prevent reuse.
  • The client stores the new access token and continues making requests.

NB: Passport.js provides a robust authentication library that simplifies this process across various frameworks.

Improving UX for Token Expiry

To avoid disruptions when tokens expire:

  • Silent Authentication: Detects token expiry errors on the client, requests a new token, and retry the failed request automatically—seamlessly handling it in the background.
  • Preemptive Token Refresh: Track token expiry on the client and refresh it before it expires. However, this method may introduce unnecessary requests, impacting performance.

This approach ensures a smooth user experience without requiring users to manually re-authenticate frequently.

Security Best Practices

Below are some of the practices in points you can consider:

  • Use HTTPS to encrypt traffic and prevent token interception.
  • Store refresh tokens securely in HTTP-only cookies to prevent XSS.
  • Use short-lived access tokens and rotate them with refresh tokens.
  • Use strong secret keys and avoid hardcoding them in the codebase.
  • Implement token revocation for logouts and compromised accounts.
  • Restrict token usage by scope and role-based access control (RBAC)

Summary

This guide gives you a heads-up for how token-based authentication works and makes it easy to understand while implementing it in any of your favorite languages.

Cornelius Emase

About Cornelius Emase

Software Engineer | Product Manager | Technical writer |