microsoft-authentication-library-for-js: acquireTokenSilent : ERROR InteractionRequiredAuthError: no_tokens_found: No refresh token found in the cache. Please sign-in

Core Library

MSAL Node (@azure/msal-node)

Core Library Version

2.13.1

Wrapper Library

Not Applicable

Wrapper Library Version

N/A

Public or Confidential Client?

Public

Description

We are calling acquireTokenSilent to get a new token without needing the user to give permissions again, but the function throws the error acquireTokenSilent : ERROR InteractionRequiredAuthError: no_tokens_found: No refresh token found in the cache. Please sign-in

Error Message

Error silently: InteractionRequiredAuthError: no_tokens_found: No refresh token found in the cache. Please sign-in.

MSAL Logs

[Tue, 10 Sep 2024 19:11:02 GMT] : [] : @azure/msal-common@14.14.2 : Info - CacheManager:getIdToken - Returning ID token
[Tue, 10 Sep 2024 19:11:02 GMT] : [edf00ed8-1a30-462a-b1da-04e9ac1bb8e5] : @azure/msal-node@2.13.1 : Info - Building oauth client configuration with the following authority: https://login.microsoftonline.com/TENANT_I/oauth2/v2.0/token.
[Tue, 10 Sep 2024 19:11:02 GMT] : [edf00ed8-1a30-462a-b1da-04e9ac1bb8e5] : @azure/msal-common@14.14.2 : Info - Token refresh is required due to cache outcome: 1
[Tue, 10 Sep 2024 19:11:02 GMT] : [] : @azure/msal-common@14.14.2 : Info - CacheManager:getRefreshToken - No refresh token found.
Error silently: InteractionRequiredAuthError: no_tokens_found: No refresh token found in the cache. Please sign-in.

Network Trace (Preferrably Fiddler)

  • Sent
  • Pending

MSAL Configuration

export const msalConfig = (
  supabase: SupabaseClient,
  userId: string,
): Configuration => {
  return {
    auth: {
      clientId: process.env.OUTLOOK_CLIENT_ID || "",
      clientSecret: process.env.OUTLOOK_CLIENT_SECRET,
      authority:
        `https://login.microsoftonline.com/${process.env.OUTLOOK_TENANT_ID}`,
    },
    cache: {
      cachePlugin: new SupabaseCachePlugin(supabase, userId),
    },
    system: {
      loggerOptions: {
        loggerCallback(
          loglevel: LogLevel,
          message: string,
          containsPii: boolean,
        ) {
          console.log(message);
        },
        piiLoggingEnabled: false,
        logLevel: LogLevel.Info,
      },
    },
  };
};

Relevant Code Snippets

export class SupabaseCachePlugin implements ICachePlugin {
  private supabase: SupabaseClient;
  private userId: string;

  constructor(supabase: SupabaseClient, userId: string) {
    this.supabase = supabase;
    this.userId = userId;
  }

  async beforeCacheAccess(cacheContext: TokenCacheContext): Promise<void> {
    // Load the cache from Supabase for the specific user

    console.log("beforeCacheAccess", cacheContext);
    const { data, error } = await this.supabase
      .from("msal_cache")
      .select("cache_data")
      .eq("user_id", this.userId)
      .single();

    if (data && !error) {
      cacheContext.tokenCache.deserialize(data.cache_data);
    }
  }

  async afterCacheAccess(cacheContext: TokenCacheContext): Promise<void> {
    if (cacheContext.cacheHasChanged) {
      // Save the updated cache to Supabase for the specific user
      const serializedCache = cacheContext.tokenCache.serialize();
      await this.supabase
        .from("msal_cache")
        .upsert({
          user_id: this.userId,
          cache_data: serializedCache,
        });
    }
  }
}

Reproduction Steps

  1. Successful login using the following scope [“openid”,“profile”,“Calendars.Read”,“Calendars.ReadWrite”, “email”,“user.read”,“offline_access”]
  2. Call AcquireTokenSilent function

Expected Behavior

we should be able to get a new token.

Identity Provider

Entra ID (formerly Azure AD) / MSA

Browsers Affected (Select all that apply)

None (Server)

Regression

N/A

Source

External (Customer)

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 1
  • Comments: 30 (12 by maintainers)

Commits related to this issue

Most upvoted comments

If it helps anyone, 7 days of pain was caused by including the https:// protocol in the knownAuthorities property value in the MSAL instance Configuration object:

auth: {
    clientId: process.env.APP_CLIENT_ID_B2C_SignIn,
    clientSecret: process.env.APP_CLIENT_SECRET_B2C_SignIn,
    authority: process.env.POLICY_AUTHORITY_B2C_SIGN_IN,
    knownAuthorities: [process.env.AUTHORITY_DOMAIN_B2C_SignIn] // this must be an array, and the domain should not include the 'https://' prefix!!!!!
}

For some reason, prior to MSAL Node 3.2.0 this did not cause a problem when calling acquireTokenSilent, from 3.2.0 onwards it resulted in:

InteractionRequiredAuthError: no_tokens_found: No refresh token found in the cache. Please sign-in.

So maybe the incorrect value messed up acquireTokenSilent being able to find a match between the account object it was passed and the token cache.

I also had a deprecated property in the config which I removed, not sure if that made a difference though:

validateAuthority: false

and I removed the redirectUri property, as it doesn’t belong in the MSAL instance Configuration object.

Posting in case this helps anyone else.

I was also running into the error

ERROR InteractionRequiredAuthError: no_tokens_found: No refresh token found in the cache.

Along the lines of @KarishmaGhiya’s solution above, I did some debugging and found that this is happens under the following circumstance;

  1. You are creating a new instance of the msal client like const msalInstance = new ConfidentialClientApplication(msalConfig(supabase, userId));
  2. When you call msalInstance.acquireTokenSilent(), the msalInstance.tokenCache does not automatically hydrate from the provided cache (e.g Redis).

As @KarishmaGhiya’s fix has not been merged, a workaround I’m using is just to have a method like

export const getMsalInstance = async (userId) => {
    const msalInstance = new ConfidentialClientApplication(getMsalConfig(userId))
    await msalInstance.tokenCache.getAllAccounts()
    return msalInstance;
};

This is to be used anytime an msalInstance is required. Calling getAllAccounts() here forces the in memory cache to be updated from the persistent storage.

@bgavrilMS Apologies for the late reply but you can use this project to reproduce the error

Folks, we have not been able to reproduce this issue. Can someone please provide a minimal repo? I can see in the original post a custom cache, it’s not enough to repro. Could someone pls create a small sample that reproduces the issue?

Seeing the same issue when using msal-node. Acquiring first token with acquireTokenByCode is successful but when i try to use acquireTokenSilent with the same scope and account object that i recieved from acquireTokenByCode response im seeing this error: image

Why was this clsoe?