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.

Validating access_token failed, wrong state/nonce

See original GitHub issue

I’ve integrated OAuth Implicit flow in Angular 8 App, I’ve been getting below issue initial time especially in Firefox (incognito).

Validating access_token failed, wrong state/nonce

Initial time, there is no nonce in the local storage, how can it validateNonce (angular-oauth2-oidc.js - 2358 line) execute? This method is being thrown an exception initial time.

if (this.configService.auth) {
            console.log(this.configService.auth.authRedirectUri + "*&&&&&&&&&&&&&&&&&&dd");
            this.authConfig = {
                issuer: 'https://login.microsoftonline.com/XXXXXX/v2.0',
                redirectUri: this.configService.auth.authRedirectUri,
                clientId: this.configService.auth.clientId,
                scope: 'openid profile email',
                strictDiscoveryDocumentValidation: false,
                oidc: true,
                showDebugInformation: true,
                // URL of the SPA to redirect the user after silent refresh
                // silentRefreshRedirectUri: window.location.origin + '/login.html',
            };
            this.oauthService.configure(this.authConfig);
            this.oauthService.setStorage(localStorage);
            this.oauthService.tokenValidationHandler = new JwksValidationHandler();
            this.oauthService.setupAutomaticSilentRefresh();
            // this.oauthService.silentRefreshRedirectUri = window.location.origin + '/login.html';
        }

// trylogin funtion

  tryLogin(state?: any): Observable<boolean | any> {
        console.log("***********Try Login", state);
        return Observable.create(observer => {
            return this.oauthService.loadDiscoveryDocument(this.configService.auth.openIdDocument).then(() => {
                console.log("***********Try Login", state);
                return this.oauthService.tryLogin({}).then(() => {
                    observer.next(state ? state : this.isLoggedIn);
                    observer.complete();
                }).catch(err => {
                    observer.error(err);
                    observer.complete();
                });
            });
        });
    } 

Desktop (please complete the following information):

  • OS: Mac, Windows
  • Browser Firefox
  • Version Latest

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:4
  • Comments:37 (2 by maintainers)

github_iconTop GitHub Comments

4reactions
remkoboschkercommented, Feb 5, 2021

I wrote a workaround that stores the nonce and pkce verifier in localstorage. I would like to understand what’s going on and why only firefox. I suspect maybe firefox handels localhost differently. Anyhow I implemented the OAuthStorage class like this and provided it in my core module.

export class LocalNonceStorage implements OAuthStorage {
   private needsLocal(key: string) {
        return key === 'nonce' || key === 'PKCE_verifier';
    }
    getItem(key: string) {
        if (this.needsLocal(key)) {
            return localStorage.getItem(key);
        }
        return sessionStorage.getItem(key);
    }
    removeItem(key: string) {
        if (this.needsLocal(key)) {
            return localStorage.removeItem(key);
        }
        return sessionStorage.removeItem(key);
    }
    setItem(key: string, data: string) {
        if (this.needsLocal(key)) {
            return localStorage.setItem(key, data);
        }
        return sessionStorage.setItem(key, data);
    }
}

export function storageFactory(localNonceStorage: LocalNonceStorage): OAuthStorage {
    return localNonceStorage;
}

export class CoreModule {
    static forRoot(): ModuleWithProviders<CoreModule> {
        return {
            ngModule: CoreModule,
            providers: [        
                { provide: LocalNonceStorage, useClass: LocalNonceStorage },
                { provide: AuthConfig, useValue: authConfig },
                { provide: OAuthModuleConfig, useValue: authModuleConfig },
                { provide: OAuthStorage, useFactory: storageFactory, deps: [LocalNonceStorage] }]
        };
    }

    constructor(@Optional() @SkipSelf() parentModule: CoreModule) {
        if (parentModule) {
            throw new Error('CoreModule is already loaded. Import it in the AppModule only');
        }
    }
}
3reactions
schanzencommented, Aug 5, 2020

EDIT: I managed to get it to work using https://github.com/manfredsteyer/angular-oauth2-oidc/issues/728#issuecomment-590909947. This should still be fixed or documented somewhere that it is necessary.

The ability to disable the nonce check might not be feasible, If I recall correctly it’s mandatory by the spec?

Certainly there should be either:

* no error (i.e. there might still be a bug in the library)

* a _descriptive_ error explaining that something was misconfigured in the _app_, in a way that helps resolve the issue

However, I am thinking about closing this specific issue. The original poster never responded anymore or tried Manfred’s suggestion. Others commenting later about having the same symptom might or might not experience the same cause, but we have no up to date reproducible scenario. So it might be better if someone opens a fresh issue with a reproducible scenario using the latest version of the library (or at the least post one in this issue), so we can trace the cause and fix that?

Again, by no means do I want to say that “there’s no issue”, I’m just looking for the clearest, most efficient path to getting a repro, and ultimately getting things resolved.

Just created a fresh project using angular CLI and followed the minimal example and getting this error. The local storage is empty (no state stored). So this is definitely a bug. Currently I am testing on localhost.

The nonce is not mandatory in OIDC and definitely not in RFC 6749. Not sure about the current security BCP draft right now. Anyway. Still a bug no matter how the plugin handles and interprets the state parameter. But basically it currently enforces the use of a nonce which is piggybacked in the state leading to the error due to the bug.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Validating access_token failed, wrong state/nonce
I am authenticating using 'angular-oauth2-oidc' with ping federation, authentication is working good in Chrome browser but in Edge we are ...
Read more >
Angular-oauth2-oidc: Error validating tokens. Wrong nonce.
After integrating the Angular-oauth2-oidc library in our application, we got the following error message when invoking the Implicit Flow:.
Read more >
Angular UI Bug: Error Refreshing Token, Wrong State/Nonce ...
After entering credentials, verifying with two factor, and redirecting to the Angular home page, the user is still not logged in. They click ......
Read more >
Validating access_token failed, wrong state/nonce
Coming soon: A brand new website interface for an even better experience!
Read more >
IdentityServer/IdentityServer4 - Gitter
Hey guys, im trying to implement IS4 on OWIN with angular-oauth2-oidc but im getting a "Validating access_token failed, wrong state/nonce.
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