Skip to main content

The Problem

When implementing JWT authentication, you may encounter a common scenario:
  1. A user logs into your store’s mobile app while on WiFi
  2. The JWT token is issued and includes their current IP address
  3. Later, the user switches to cellular data or changes networks
  4. Their next API request fails with a 401 error, despite having a valid token
This happens because the JWT token includes IP validation as a security measure to prevent token theft and replay attacks. When the user’s IP address changes, the security check fails.

Common Scenarios That Trigger This

  • Switching between WiFi and cellular data
  • Moving between different WiFi networks
  • Using the app while commuting
  • VPN connections being enabled or disabled

Solution Overview

This guide demonstrates how to implement a robust token validation and refresh flow that:
  1. Detects when a token becomes invalid
  2. Automatically refreshes the token without disrupting the user experience
  3. Falls back to re-authentication only when necessary

How to setup?

This guide shows how to implement secure token handling using HTTP-only cookies.
Ensure your server is configured to set secure HttpOnly cookies with appropriate SameSite attributes.

1. Validate the token

First, check if the current token is still valid using the validation endpoint:

2. Implementation Token Refresh

When validation fails, implement the refresh flow:

3. Complete Error Handler

Implementation Example

Server-Side Configuration

Your server should set cookies with secure options:

Security Considerations

  • Cookies are automatically sent with requests to your domain
  • HttpOnly prevents XSS attacks from stealing tokens
  • SameSite=Strict prevents CSRF attacks
  • Secure flag ensures cookies only work over HTTPS
  • No client-side token storage needed

Error Response

The API returns a standardized error response: