AzureAD / microsoft-authentication-library-for-js

Microsoft Authentication Library (MSAL) for JS
http://aka.ms/aadv2
MIT License
3.64k stars 2.65k forks source link

BrowserAuthError: no_token_request_cache_error: No token request found in cache #6790

Closed vinothkummar closed 8 months ago

vinothkummar commented 9 months ago

Core Library

MSAL.js (@azure/msal-browser)

Core Library Version

"@azure/msal-browser": "^2.22.1"

Wrapper Library

MSAL Angular (@azure/msal-angular)

Wrapper Library Version

"@azure/msal-angular": "^2.1.2",

Public or Confidential Client?

Public

Description

After login with the credentials it is keep redirecting to the same page again in a loop and the policy behind custom policy in order for me to set up the office 365 identity provider sign up. => this is behaviour I see it in the edge browser.

If I run the application in the visual studio code debut mode and which open in the open chrome browser; it takes credentials and throws error BrowserAuthError: no_token_request_cache_error: No token request found in cache. at BrowserAuthError.AuthError [as constructor] (AuthError.js:27:24) at new BrowserAuthError (BrowserAuthError.js:197:28) at BrowserAuthError.createNoTokenRequestCacheError (BrowserAuthError.js:354:16) at BrowserCacheManager.getCachedRequest (BrowserCacheManager.js:802:19) at RedirectClient. (RedirectClient.js:222:61) at step (_tslib.js:75:23) at Object.next (_tslib.js:56:53) at _tslib.js:49:71 at new ZoneAwarePromise (zone.js:1427:29) at __awaiter (_tslib.js:45:12)

Error: Uncaught (in promise): ClientAuthError: state_not_found: State not found: Cached State ClientAuthError: state_not_found: State not found: Cached State at ClientAuthError.AuthError [as constructor] (AuthError.js:27:24) at new ClientAuthError (ClientAuthError.js:206:28) at ClientAuthError.createStateNotFoundError (ClientAuthError.js:282:16) at RedirectHandler. (RedirectHandler.js:96:35) at step (_tslib.js:75:23) at Object.next (_tslib.js:56:53) at _tslib.js:49:71 at new ZoneAwarePromise (zone.js:1427:29) at __awaiter (_tslib.js:45:12) at RedirectHandler.handleCodeResponseFromHash (RedirectHandler.js:81:25) at resolvePromise (zone.js:1211:31) at zone.js:1118:17 at zone.js:1134:33 at _ZoneDelegate.invoke (zone.js:372:26) at Object.onInvoke (core.mjs:26491:33) at _ZoneDelegate.invoke (zone.js:371:52) at Zone.run (zone.js:134:43) at zone.js:1275:36 at _ZoneDelegate.invokeTask (zone.js:406:31) at Object.onInvokeTask (core.mjs:26478:33)

MSAL Configuration

export const environment = {
  production: false,
  mockServer: false,
  webapi: "https://localhost:55376/api/v1/",
  webapibase: "https://localhost:55376",
  i18n: "assets/i18n/",
  brokerStylesPath: "",
  webapiversion: "1",
  auth: {
    scopes: ['https://EmporosClientPortalQAT.b2clogin.com/0c1439c2-8fea-4c39-9a2d-2791cb535902/access_as_user'],
    clientId: "0c1439c2-8fea-4c39-9a2d-2791cb535902",
    authDomain: "https://EmporosClientPortalQAT.b2clogin.com/",
    baseAuthority: "https://EmporosClientPortalQAT.b2clogin.com/EmporosClientPortalQAT.onmicrosoft.com/B2C_1A_",
    knownAuthorities: ["EmporosClientPortalQAT.b2clogin.com"],
    redirectUri: "http://localhost:4200",
    postLogoutRedirectUri: "http://localhost:4200",
    azureRedirectUri: "http://localhost:4200",
    subdomainRedirectUri: "",
  },
  files: {
    maxfileSize: 5242880
  }
};

Relevant Code Snippets

import { NgModule, APP_INITIALIZER } from '@angular/core';
import { IPublicClientApplication, PublicClientApplication, 
    BrowserCacheLocation,
    InteractionType,
    Configuration} from '@azure/msal-browser';
import { MsalGuard, MsalInterceptor, MsalBroadcastService,
     MsalInterceptorConfiguration, MsalModule, MsalService,
      MSAL_GUARD_CONFIG, MSAL_INSTANCE, MSAL_INTERCEPTOR_CONFIG, 
      MsalGuardConfiguration } from '@azure/msal-angular';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { ConfigService } from './msal-config.service';
import { environment } from '../../../../environments/environment';

const environmentAuth = { ...environment.auth };

export function initializerFactory(configService: ConfigService): any {
  const promise = configService.init().then((value) => {

    });
    return () => promise;
}

export function MSALInstanceFactory(configService: ConfigService): IPublicClientApplication {
  let config = msalConfig;
  config.auth.authority = configService.getAuthority();
  config.auth.redirectUri = configService.getRedirectPath();
  config.auth.postLogoutRedirectUri = configService.getLogoutPath();

  return new PublicClientApplication(config);
}

export function MSALInterceptorConfigFactory(config: ConfigService): MsalInterceptorConfiguration {
  const protectedResourceMap = new Map<string, Array<string>>();
  protectedResourceMap.set(environment.webapi, environmentAuth.scopes);

    return {
      interactionType: InteractionType.Redirect,
      protectedResourceMap,
      authRequest: {
        authority: config.getAuthority(),
        redirectUri: config.getRedirectPath(),
      }
    };
  }

export function MSALGuardConfigFactory(config: ConfigService): MsalGuardConfiguration {
  return {
      interactionType: InteractionType.Redirect,
      loginFailedRoute: config.getRedirectPath(),

      authRequest: {
        authority: config.getAuthority(),
        redirectUri: config.getRedirectPath(),
        scopes: environmentAuth.scopes
      }
  };
}

export const msalConfig: Configuration = {
  auth: environmentAuth,
  cache: {
    cacheLocation: BrowserCacheLocation.SessionStorage,
    storeAuthStateInCookie: false,
    secureCookies: false
  },
  system: {
    loggerOptions: {
      loggerCallback: (level: any, message: any, containsPii: any) => {
        if (containsPii) {
          return;
        }
      },
      piiLoggingEnabled: false
    }
  }
};

@NgModule({
    providers: [],
    imports: [MsalModule]
})
export class MsalConfigDynamicModule {

  static forRoot() {
        return {
            ngModule: MsalConfigDynamicModule,
            providers: [
                ConfigService,

                {
                    provide: APP_INITIALIZER, useFactory: initializerFactory,
                    deps: [ConfigService],
                    multi: true
                },
                {
                    provide: MSAL_INSTANCE,
                    useFactory: MSALInstanceFactory,
                    deps: [ConfigService]
                },
                {
                    provide: MSAL_GUARD_CONFIG,
                    useFactory: MSALGuardConfigFactory,
                    deps: [ConfigService]
                },
                {
                    provide: MSAL_INTERCEPTOR_CONFIG,
                    useFactory: MSALInterceptorConfigFactory,
                    deps: [ConfigService]
                },
                MsalService,
                MsalGuard,
                MsalBroadcastService,
                {
                    provide: HTTP_INTERCEPTORS,
                    useClass: MsalInterceptor,
                    multi: true
                }
            ]
        };
    }
}

Identity Provider

Azure B2C Custom Policy

Source

External (Customer)

please help to resolve this and I have gone through all you previous response but non of them helps me in order resolve the issue. I'm stuck in this issue almost 3 weeks.

amanvermaa commented 9 months ago

This might be happening because of 'authority mismatch error'. The account that you might be setting as the active account might be of different tenant than the tenant you're logging in. Please update the active account with the account which of the same tenant. To be specific, you need to update your checkAndSetActiveAccount() function in the app.component.ts

This is how I modified it in my usecase :

checkAndSetActiveAccount() {
    let activeAccount: AccountInfo | null = this.authService.instance.getActiveAccount();
    let accounts = this.authService.instance.getAllAccounts();
    let tenantAccounts = accounts.filter(x => x.tenantId == environment.tenantId);

    if (activeAccount && activeAccount.tenantId != environment.tenantId && tenantAccounts && tenantAccounts.length > 0) {
      this.authService.instance.setActiveAccount(tenantAccounts[0]);
    }
    else if (!activeAccount && accounts.length > 0) {
      this.authService.instance.setActiveAccount(tenantAccounts[0]);
    }
    else if (!activeAccount && accounts.length == 0) {
      this.loginRedirect();
    }

    this.checkIfActiveAccountExists();  //Function just used for routing in case active account is set
  }
ch-tactica commented 9 months ago

I've been hitting this error a lot intermittently, it seems to go away eventually on it's own, or when user's purge their local storage, active account is of the same tenant.

tnorling commented 8 months ago

These errors mean that sessionStorage has been cleared of temporary artifacts before MSAL has had a chance to retrieve them. If you're hitting this intermittently it likely means you have a race condition somewhere. You should debug and see if you can trace where the storage entries are cleared.

I'd also recommend upgrading to the latest version as we've had bugs related to temp storage in the past which have since been resolved.

vinothkummar commented 8 months ago

Hi all, Thank you for your helping comments but still my issues are not resolved I'll be adding more details and some error logs .

Please leave my issue open now. thank you

vinothkummar commented 8 months ago

After I logged in and I can see this eventtype message

{"eventType":"msal:loginSuccess","interactionType":"redirect","payload":{"authority":"https://emporosclientportalqat.b2clogin.com/emporosclientportalqat.onmicrosoft.com/b2c_1a_goldhawk/","uniqueId":"09244327-b1f7-4204-8942-367d983d822f","tenantId":"f76bec21-6080-4557-855a-2967f03aba9e","scopes":[],"account":{"homeAccountId":"09244327-b1f7-4204-8942-367d983d822f-b2c_1a_goldhawk.f76bec21-6080-4557-855a-2967f03aba9e","environment":"emporosclientportalqat.b2clogin.com","tenantId":"f76bec21-6080-4557-855a-2967f03aba9e","username":"","localAccountId":"09244327-b1f7-4204-8942-367d983d822f","name":"VINOTH","idTokenClaims":{"ver":"1.0","iss":"https://emporosclientportalqat.b2clogin.com/f76bec21-6080-4557-855a-2967f03aba9e/v2.0/","sub":"09244327-b1f7-4204-8942-367d983d822f","aud":"0c1439c2-8fea-4c39-9a2d-2791cb535902","exp":1707344672,"nonce":"db9d4dfb-36f4-4fa6-bc0b-c620393d9fc2","iat":1707341072,"auth_time":1707341070,"email":"vinothkummar@hotmail.com","name":"VINOTH","given_name":"KUMAR","family_name":"SUBRAMANIAN","tid":"f76bec21-6080-4557-855a-2967f03aba9e","tfp":"B2C_1A_Goldhawk","nbf":1707341072}},"idToken":"eyJhbGciOiJSUzI1NiIsImtpZCI6Im1YR29yNzNwa3laUGVWa18wQXpHR3hJVTBpcXRPQmY1UjFBV2dWSVJrOUUiLCJ0eXAiOiJKV1QifQ.eyJ2ZXIiOiIxLjAiLCJpc3MiOiJodHRwczovL2VtcG9yb3NjbGllbnRwb3J0YWxxYXQuYjJjbG9naW4uY29tL2Y3NmJlYzIxLTYwODAtNDU1Ny04NTVhLTI5NjdmMDNhYmE5ZS92Mi4wLyIsInN1YiI6IjA5MjQ0MzI3LWIxZjctNDIwNC04OTQyLTM2N2Q5ODNkODIyZiIsImF1ZCI6IjBjMTQzOWMyLThmZWEtNGMzOS05YTJkLTI3OTFjYjUzNTkwMiIsImV4cCI6MTcwNzM0NDY3Miwibm9uY2UiOiJkYjlkNGRmYi0zNmY0LTRmYTYtYmMwYi1jNjIwMzkzZDlmYzIiLCJpYXQiOjE3MDczNDEwNzIsImF1dGhfdGltZSI6MTcwNzM0MTA3MCwiZW1haWwiOiJ2aW5vdGhrdW1tYXJAaG90bWFpbC5jb20iLCJuYW1lIjoiVklOT1RIIiwiZ2l2ZW5fbmFtZSI6IktVTUFSIiwiZmFtaWx5X25hbWUiOiJTVUJSQU1BTklBTiIsInRpZCI6ImY3NmJlYzIxLTYwODAtNDU1Ny04NTVhLTI5NjdmMDNhYmE5ZSIsInRmcCI6IkIyQ18xQV9Hb2xkaGF3ayIsIm5iZiI6MTcwNzM0MTA3Mn0.MQiU3W94vCSFkLlHHK6y63fcmmEumKyQDTe_JYM6HpH4VH1isvZW5WnTg4y5kiMcdoIxHP_zyxkUWdkTWN5jqes-uU7etLlI1jLZQsPYcYA5rTv77aENwkGtxR0aT3b9w93Uoos8ZcaqV-6g4XoxYUtOO3Fsx6i4v17KoCh_d4_rfv0buDGnS6KkaZM_wLG7kmXOOJwnKEEjSKkhNvsKH8fJwXe636YqAoMG9_MMJuKdPxH-IXcNuMEmnnCFv3zKGLImCCmfn_4ECWrNIEFcawDVL_zy_vFlpWjqNDAPVyL8CvnTLJq73_ooc_BBMqP4G1pReK-0IcLsgk5JYuOG2w","idTokenClaims":{"ver":"1.0","iss":"https://emporosclientportalqat.b2clogin.com/f76bec21-6080-4557-855a-2967f03aba9e/v2.0/","sub":"09244327-b1f7-4204-8942-367d983d822f","aud":"0c1439c2-8fea-4c39-9a2d-2791cb535902","exp":1707344672,"nonce":"db9d4dfb-36f4-4fa6-bc0b-c620393d9fc2","iat":1707341072,"auth_time":1707341070,"email":"vinothkummar@hotmail.com","name":"VINOTH","given_name":"KUMAR","family_name":"SUBRAMANIAN","tid":"f76bec21-6080-4557-855a-2967f03aba9e","tfp":"B2C_1A_Goldhawk","nbf":1707341072},"accessToken":"","fromCache":false,"expiresOn":null,"correlationId":"c179bfe1-4541-478c-9c74-62e76285b9d3","familyId":"","tokenType":"","state":"","cloudGraphHostName":"","msGraphHost":"","fromNativeBroker":false},"error":null,"timestamp":1707341073615}

At the same time if i look in to the network tab

https://emporosclientportalqat.b2clogin.com/emporosclientportalqat.onmicrosoft.com/b2c_1a_goldhawk/oauth2/v2.0/token this call returns 200 and the payload what is been passed eyJraWQiOiJYdmJ4dzQ0Z09Denh5amdtWFJRdjlFQS1jY1dYa29zWnFjZjhrN2xQdVRNIiwidmVyIjoiMS4wIiwiemlwIjoiRGVmbGF0Z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5PNuv2r-dYWEWsgylhreHwGKHaOVN35Dea78igLPjxNNznZi763DZxSw1PfhhLdz4P70NBnOWkGH4NVzAfcU6Xmsz5Xr7jAmzqZk3ZqcAH5lslGaWIdDf3Mi3Uh8Ku5biC0uRe-Ox0jd8.JPE7dlg--4IwlXlPv5I5nw

vinothkummar commented 8 months ago

{"eventType":"msal:acquireTokenSuccess","interactionType":"silent","payload":{"authority":"https://emporosclientportalqat.b2clogin.com/emporosclientportalqat.onmicrosoft.com/b2c_1a_goldhawk/","uniqueId":"09244327-b1f7-4204-8942-367d983d822f","tenantId":"f76bec21-6080-4557-855a-2967f03aba9e","scopes":[],"account":{"homeAccountId":"09244327-b1f7-4204-8942-367d983d822f-b2c_1a_goldhawk.f76bec21-6080-4557-855a-2967f03aba9e","environment":"emporosclientportalqat.b2clogin.com","tenantId":"f76bec21-6080-4557-855a-2967f03aba9e","username":"","localAccountId":"09244327-b1f7-4204-8942-367d983d822f","name":"VINOTH","idTokenClaims":{"ver":"1.0","iss":"https://emporosclientportalqat.b2clogin.com/f76bec21-6080-4557-855a-2967f03aba9e/v2.0/","sub":"09244327-b1f7-4204-8942-367d983d822f","aud":"0c1439c2-8fea-4c39-9a2d-2791cb535902","exp":1707345294,"nonce":"db9d4dfb-36f4-4fa6-bc0b-c620393d9fc2","iat":1707341694,"auth_time":1707341070,"email":"vinothkummar@hotmail.com","name":"VINOTH","given_name":"KUMAR","family_name":"SUBRAMANIAN","tid":"f76bec21-6080-4557-855a-2967f03aba9e","tfp":"B2C_1A_Goldhawk","nbf":1707341694}},"idToken":"eyJhbGciOiJSUzI1NiIsImtpZCI6Im1YR29yNzNwa3laUGVWa18wQXpHR3hJVTBpcXRPQmY1UjFBV2dWSVJrOUUiLCJ0eXAiOiJKV1QifQ.eyJ2ZXIiOiIxLjAiLCJpc3MiOiJodHRwczovL2VtcG9yb3NjbGllbnRwb3J0YWxxYXQuYjJjbG9naW4uY29tL2Y3NmJlYzIxLTYwODAtNDU1Ny04NTVhLTI5NjdmMDNhYmE5ZS92Mi4wLyIsInN1YiI6IjA5MjQ0MzI3LWIxZjctNDIwNC04OTQyLTM2N2Q5ODNkODIyZiIsImF1ZCI6IjBjMTQzOWMyLThmZWEtNGMzOS05YTJkLTI3OTFjYjUzNTkwMiIsImV4cCI6MTcwNzM0NTI5NCwibm9uY2UiOiJkYjlkNGRmYi0zNmY0LTRmYTYtYmMwYi1jNjIwMzkzZDlmYzIiLCJpYXQiOjE3MDczNDE2OTQsImF1dGhfdGltZSI6MTcwNzM0MTA3MCwiZW1haWwiOiJ2aW5vdGhrdW1tYXJAaG90bWFpbC5jb20iLCJuYW1lIjoiVklOT1RIIiwiZ2l2ZW5fbmFtZSI6IktVTUFSIiwiZmFtaWx5X25hbWUiOiJTVUJSQU1BTklBTiIsInRpZCI6ImY3NmJlYzIxLTYwODAtNDU1Ny04NTVhLTI5NjdmMDNhYmE5ZSIsInRmcCI6IkIyQ18xQV9Hb2xkaGF3ayIsIm5iZiI6MTcwNzM0MTY5NH0.kvI8EeyMAtjvL7y7MzClzBj51aC179HKRjHhMPHo3oAvGkhMAIB2bMyJsdSnDWWWR1QGR0rO-tjqfiQF807Bxq2f_nvxeBgFY3NpOFcJu1o9TFzEhsrHm-JpbTxbEIz6YepO8nzRBd1yzXpQAqxeBu7svq39Fjw6PsfhE0s5l9rr1nUM5ezXFIJm_h7qQU36pn2Sv8RemIZ9tPcjypVZqhEoP5XZItqk9A1FGWKdc7F3_ZLxmX92T57dm6sG7jeU8WspB4ksmDggtFDBRDiS7e-f1DOH-xRbszYZjZeq2eR--qBZpkxBgh2EFd7NyZ3PkpC1CW5WNTR1uDB3IBUb2A","idTokenClaims":{"ver":"1.0","iss":"https://emporosclientportalqat.b2clogin.com/f76bec21-6080-4557-855a-2967f03aba9e/v2.0/","sub":"09244327-b1f7-4204-8942-367d983d822f","aud":"0c1439c2-8fea-4c39-9a2d-2791cb535902","exp":1707345294,"nonce":"db9d4dfb-36f4-4fa6-bc0b-c620393d9fc2","iat":1707341694,"auth_time":1707341070,"email":"vinothkummar@hotmail.com","name":"VINOTH","given_name":"KUMAR","family_name":"SUBRAMANIAN","tid":"f76bec21-6080-4557-855a-2967f03aba9e","tfp":"B2C_1A_Goldhawk","nbf":1707341694},"accessToken":"","fromCache":false,"expiresOn":null,"correlationId":"3f0b1ff1-eb54-4f99-a335-84c6e3ac45db","familyId":"","tokenType":"","state":"","cloudGraphHostName":"","msGraphHost":"","fromNativeBroker":false},"error":null,"timestamp":1707341695623}

vinothkummar commented 8 months ago

But it is keep repeating the loop cycle msalacquiretokensuccess

khRasikh commented 2 months ago

Using the following Azure dependecies in Nextjs:

"@azure/msal-browser": "^3.11.0", "@azure/msal-node": "^2.6.5", "@azure/msal-react": "^2.0.13",

` There is still the issue:

BrowserAuthError: no_token_request_cache_error: No token request found in cache. at c (701-09290108fa8b325.js:7:122739) at G.getCachedRequest (701-09290108fa8b325.js:5:25662) at handleResponse (701-09290108fa8b325.js:17:69220) at ev.handleRedirectPromise (701-09290108fa8b325.js:17:66959) at 701-09290108fa8b325.js:15:61188 at h3.handleRedirectPromise (701-09290108fa8b325.js:7:8796) at u.handleRedirectPromise (701-09290108fa8b325.js:1:54933) at 701-09290108fa8b325.js:17:208113 `