question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Access token caching is not working

See original GitHub issue

Library

  • msal@1.x.x or @azure/msal@1.x.x
  • @azure/msal-browser@2.x.x
  • @azure/msal-node@1.x.x
  • @azure/msal-react@1.x.x
  • @azure/msal-angular@0.x.x
  • @azure/msal-angular@1.x.x
  • @azure/msal-angular@2.x.x
  • @azure/msal-angularjs@1.x.x

Framework

  • Angular 11
  • React
  • Other

Description

The caching of the access token is not working. On every intercepted XHR-Request the msal lib is requesting a new access token.

Networktraffic looks like: POST /oauth2/v2.0/token GET /some-xhr POST /oauth2/v2.0/token POST /some-other-xhr POST /oauth2/v2.0/token GET /some-xhr

Error Message

MSAL Configuration

export const appInitializer = (moduleType: Type<any>): Promise<void> => fetch('/initialize')
  .then(response => response.json())
  .then(initialConfig => {
    const authCfg = initialConfig.ciamOptions;
    const msalConfig: Configuration = {
      auth: {
        clientId: authCfg.clientId as string,
        authority: `https://${authCfg.tenantName}.b2clogin.com/${authCfg.tenantName}.onmicrosoft.com/${authCfg.signInPolicy}`,
        redirectUri: /.*:\/\/[^\/]+(?:\/admin|\/studio)?/.exec(location.href)[0],
        knownAuthorities: [`${authCfg.tenantName}.b2clogin.com`],
      },
      system: {
        loggerOptions: {
          logLevel: LogLevel.Verbose,
          piiLoggingEnabled: true,
          loggerCallback: (level, msg) => {
            console.log(msg)
          }
        }
      },
      cache: {
        cacheLocation: BrowserCacheLocation.LocalStorage,
      },
    };

    /**
     * 00000000-0000-0000-0000-000000000000 -
     * Using the client ID as the scope indicates that your app needs an access token that can be used
     * against your own service or web API, represented by the same client ID.
     */
    const scopes = [authCfg.clientId];


    const protectedResourceMap = new Map();
    protectedResourceMap.set(`/api/*`, scopes);

    const msalConfigAngular: MsalInterceptorConfiguration = {
      interactionType: InteractionType.Redirect,
      protectedResourceMap
    };

    const msalGuardFactory = (): MsalGuardConfiguration => ({
      interactionType: InteractionType.Redirect,
      authRequest: {
        scopes
      },
    });

    platformBrowserDynamic(
      [
        {
          provide: MSAL_INSTANCE,
          useValue: new PublicClientApplication(msalConfig)
        },
        {
          provide: MSAL_INTERCEPTOR_CONFIG,
          useValue: msalConfigAngular
        },
        {
          provide: MSAL_GUARD_CONFIG,
          useFactory: msalGuardFactory
        }
      ]
    ).bootstrapModule(moduleType)
      // eslint-disable-next-line no-console
      .catch(err => console.error(err));
  });

Reproduction steps

Expected behavior

The POST /oauth2/v2.0/token should only occur if the access token is expired, other wiese the token should be taken from the local storage.

Identity Provider

  • Azure AD
  • Azure B2C Basic Policy
  • Azure B2C Custom Policy
  • ADFS
  • Other

Browsers/Environment

  • Chrome
  • Firefox
  • Edge
  • Safari
  • IE
  • Other (Please add browser name here)

Regression

  • Did this behavior work before? Version:

Security

  • Is this issue security related?

Source

  • Internal (Microsoft)
  • Customer request

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
pkanher617commented, Feb 19, 2021

Great! Closing for now since issue was resolved, open another issue if you are still having problems. Thanks!

1reaction
simon-ittmanncommented, Feb 19, 2021

@pkanher617 With a custom scope the caching is working fine 👍 Thank you 😃

Read more comments on GitHub >

github_iconTop Results From Across the Web

Why caching access token is consider bad in oauth2?
Caching access token will work but then you will have to query the cache on each request.
Read more >
Acquire and cache tokens with Microsoft Authentication ...
MSAL maintains a token cache (or two caches for confidential client applications) and caches a token after it's been acquired. In many cases, ......
Read more >
Invoking OAuth and Caching Access Tokens - Fiorano Software
For APIs secured with OAuth, Access Token is obtained from the token endpoint provided and passed on to the API with every request....
Read more >
Caching Management API Access Tokens in Login Action
Problem statement: How do I cache a Management API access token(s) using the Node Management Client and Actions caching functionality?
Read more >
Access Token Not Found In Cache - Vela Cloud
This data allows your app to do intelligent caching of access tokens without having to parse the access token itself. From a high...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found