How to Manage Invalid Tokens in Web and Mobile Applications

Photo by Kyle Glenn on Unsplash

How to Manage Invalid Tokens in Web and Mobile Applications

The different strategies that developers can use to manage invalid tokens issued by OpenID Connect flow in web and mobile apps.

As web and mobile applications become increasingly reliant on third-party APIs, it's critical to manage the tokens issued by OpenID Connect flows effectively. Tokens are used to authenticate and authorize users, and when they become invalid, they can cause a range of problems, including failed requests, security vulnerabilities, and poor user experience.

OpenID Connect is an authentication protocol built on top of OAuth2 that enables clients to verify the identity of end-users based on the authentication performed by an authorization server. When a user logs in to an application that uses OpenID Connect, the authorization server issues an access token that the application uses to access the user's resources on the API.

When the access token becomes invalid, it's essential to detect and manage the issue effectively to ensure that the user's experience is not negatively affected. In the following sections, we'll discuss different approaches to detecting and managing invalid tokens in web and mobile applications.

Detecting Invalid Tokens

Detecting invalid tokens is the first step in effectively managing them. An invalid token is one that has expired, been revoked, or is otherwise invalid according to the authentication server's rules. The most common technique for detecting invalid tokens is to make a request to the authentication server and check the response.

There are two types of invalid tokens that can be detected:

  • HTTP Response Codes: Another way to detect an invalid token is by examining the HTTP response codes from the resource server. If the resource server returns a 401 Unauthorized response code, it is an indication that the token is invalid or has expired. In this case, the client should request a new access token using one of the strategies we'll discuss in the next section.

  • Expired Tokens: Access tokens have a limited lifespan, typically measured in minutes or hours. After the token has expired, it can no longer be used to access the user's resources. To detect expired tokens, the client can compare the token's expiration time with the current time on the device or server. If the token has expired, the client should request a new access token using one of the strategies we'll discuss in the next section.

  • Revoked or Invalid Tokens: Sometimes, access tokens become invalid before their expiration time. This can happen if the user revokes their consent for the application to access their resources or if the authentication server detects suspicious activity related to the token. To detect revoked or invalid tokens, the client should make a request to the token introspection endpoint provided by the authentication server. The introspection endpoint returns a JSON object that contains information about the token, including whether it's still valid.

Axios Example

By adding an interceptor to the Axios instance's response chain, we can catch 401 errors and handle them accordingly. In this case, we're logging a message indicating that the token is invalid and needs to be refreshed, and then we can proceed to request a new access token and retry the original request.

Intercepting requests in this way can be useful for handling token expiration or revocation, as well as other types of errors that may occur during API calls. It allows you to centralize your error-handling logic and avoid repeating code throughout your application.

Here's an example of how to intercept every request made with an Axios instance and handle 401 Unauthorized errors:

import axios from 'axios';

const API_URL = 'https://example.com/api';
const ACCESS_TOKEN = 'abc123'; // replace with your actual access token

const axiosInstance = axios.create({
  baseURL: API_URL,
  headers: {
    Authorization: `Bearer ${ACCESS_TOKEN}`
  }
});

axiosInstance.interceptors.response.use(
  response => response,
  error => {
    if (error.response.status === 401) {
      // handle invalid token
      console.log('Invalid token - requesting new access token');
      // request new access token and retry request
      // note: you can access the original request config with error.config
    }
    return Promise.reject(error);
  }
);

// example request
axiosInstance.get('/resource')
  .then(response => {
    // handle successful response
  })
  .catch(error => {
    // handle other errors
    console.log('Error:', error.message);
  });

Note that this approach assumes that the API server returns a 401 error code when the access token is invalid. If your API server uses a different error code to indicate an invalid token, you will need to adjust the code accordingly.

It's important to note that different authentication servers may have different rules and mechanisms for detecting invalid tokens. Developers should consult the authentication server's documentation to determine the best approach for detecting and managing invalid tokens in their particular implementation.

In the next section, we'll discuss the different strategies that developers can use to manage invalid tokens once they've been detected.

Refreshing Tokens as a Solution

Token refreshing is a common solution for handling invalid tokens in web and mobile applications that rely on OpenID Connect or OAuth. With this method, when a user's access token expires or becomes invalid, a new access token is requested without requiring the user to log in again. This allows the user to maintain their current session and continue using the application without interruption.

How Refresh Tokens Work in OpenID Connect and OAuth

In OpenID Connect and OAuth, a refresh token is issued along with an access token when a user logs in or grants access to an application. The refresh token is most of the time a long-lived token that can be used to request a new access token when the original token expires or becomes invalid. The access token is typically short-lived and has a shorter expiration time than the refresh token.

When the access token expires, the application can use the refresh token to obtain a new access token from the identity provider without requiring the user to re-authenticate. The new access token can then be used to access protected resources until it expires or becomes invalid.

Using Silent Authentication to Handle Invalid Tokens

Another solution for handling invalid tokens is to use silent authentication (aka silent login). This method allows the application to automatically refresh the access token in the background without requiring any interaction from the user.

What is a Silent Authentication?

A silent authentication is a type of flow that allows the application to automatically authenticate the user in the background without requiring the user to enter their login credentials. This is typically achieved using a refresh token or a session cookie that is stored on the user's device.

When the access token expires or becomes invalid, the application can use the fact that the user is still authenticated on the SSO to silently get a new access token in the background, without the user needing to interact with the application.

Silent Authentication with OIDC Prompt None

When using OIDC with prompt none, the authentication server can silently check whether the user has an active session without prompting the user for credentials. Here's how the process works:

The client application initiates an authorization code flow with a prompt set to none. The request might look something like this:

GET /authorize?client_id=abcd1234&redirect_uri=https://mydomain.com/callback&scope=openid%20profile&response_type=id_token&prompt=none HTTP/1.1
Host: cerberauth.com

More information about this prompt is available in this article about OpenId Connect prompts.

Re-authenticating as a Solution

If neither token refreshing nor silent logins are viable solutions, re-authentication is another option for handling invalid tokens. With this method, the user is prompted to enter their login credentials again in order to obtain a new access token.

When to Use Re-authentication?

Re-authentication should be used when token refreshing and silent logins are not feasible options. For example, if the user's refresh token has expired or the user has revoked the application's access, token refreshing may not be possible. Similarly, if the application's session cookie has expired, silent logins may not be possible.

In these cases, the user must re-authenticate in order to obtain a new access token and continue using the application.

Choosing the Right Solution for Your Application

When it comes to handling invalid tokens, there is no one-size-fits-all solution. The appropriate solution will depend on the specific needs and requirements of the application. Here are some factors to consider when choosing the right solution for your application:

Security Requirements

The security requirements of the application will play a major role in determining the appropriate solution for handling invalid tokens. If the application handles sensitive data or requires a high level of security, re-authentication may be the most appropriate solution. Alternatively, if the data is less sensitive and the priority is to maintain a seamless user experience, silent logins or token refreshing may be a better fit.

User Experience

The user experience is an important consideration when choosing a solution for handling invalid tokens. Developers should aim to minimize interruptions to the user's session and provide clear and actionable error messages when an access token becomes invalid.

Available Technologies

The available technologies and infrastructure of the application will also play a role in determining the appropriate solution. For example, if the application uses OpenID Connect or OAuth, token refreshing may be the most straightforward solution. Alternatively, if the application has a custom authentication mechanism, re-authentication may be the best option.

Compliance Requirements

If the application is subject to compliance requirements such as HIPAA or GDPR, the solution for handling invalid tokens will need to comply with those requirements. For example, GDPR requires that access tokens have a limited lifespan and that users have the right to revoke their consent at any time.

By considering these factors and evaluating the available options, developers can choose the most appropriate solution for handling invalid tokens in their applications.

Conclusion

Dealing with invalid tokens is a critical aspect of developing secure and user-friendly web and mobile applications. As we have discussed, there are several solutions available for handling invalid tokens, such as token refreshing, silent logins, and re-authentication. Developers should choose the most appropriate solution for their specific application based on factors such as security requirements, user experience, available technologies, and compliance requirements. Additionally, following best practices such as using short token expiration times, monitoring token expiration and revocation, implementing MFA, and providing clear and actionable error messages can help ensure that user sessions remain secure and uninterrupted.

By implementing these solutions and best practices, developers can provide a seamless and secure user experience while protecting their users' sensitive data.

Did you find this article valuable?

Support CerberAuth by becoming a sponsor. Any amount is appreciated!