Search code examples
angulartypescriptaws-amplifyamplify-auth-cognito

ERROR UserUnAuthenticatedException: User needs to be authenticated to call this API


currently I'm implementing an angular website where i use 'aws-amplify/auth' for authentication and I run a cognito-idp locally with localstack. I logged in into my application and after the logout I get this exception "ERROR UserUnAuthenticatedException: User needs to be authenticated to call this API."

Even when I logout with "signOut({ global: true });" I get this error. I only get this error when I load or reload my AppComponent.

I already searched the web for this error but could not find anything which works for me. I already debugged it and the error occures after the AppComponent is loaded. So I think it has nothing to do with the component.

I also rebuild and served the application, deleted all the browser cache and hard loaded the website. I expect that the application should reset and delete all the caches and chunks that the "assertAuthTokens" should not fail and return false instead or something similar.

Im Using: OS: macOS 14.2.1

npm list -g --depth=0 ├── @angular/[email protected] ├── @aws-amplify/[email protected] └── [email protected]

package-lock.json

  "name": "website",
  "version": "0.0.0",
  "dependencies": {
    "@angular/animations": "^17.1.0",
    "@angular/cdk": "^17.2.1",
    "@angular/common": "^17.1.0",
    "@angular/compiler": "^17.1.0",
    "@angular/core": "^17.1.0",
    "@angular/forms": "^17.1.0",
    "@angular/material": "^17.2.1",
    "@angular/platform-browser": "^17.1.0",
    "@angular/platform-browser-dynamic": "^17.1.0",
    "@angular/router": "^17.1.0",
    "@aws-amplify/ui-angular": "^5.0.11",
    "aws-amplify": "^6.0.18",
    "bootstrap": "^5.3.2",
    "bootstrap-icons": "^1.11.3",
    "rxjs": "~7.8.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.14.3"

This is the error log i got in the browser: enter image description here

And this is the expanded error: enter image description here

This is my AmplifyConfiguration:

=== main.ts ===
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { appConfig } from './app/app.config';
import { Amplify } from 'aws-amplify';
import { environment } from './environments/environment';

Amplify.configure({
    Auth: {
      Cognito: environment.cognito
    }
  });

bootstrapApplication(AppComponent, appConfig
).catch(err => console.error(err));

=== environment ===
export const environment = {
    production: false,
    apiUrl: 'http://127.0.0.1:3000',
    cognito: {
      region: 'us-east-1',
      userPoolId: 'us-east-1_localuserpool1',
      userPoolClientId: 'localcognitoclient1',
      userPoolEndpoint: 'http://localhost:3000/auth'
    }
  };

Thanks in advance for any help!


Solution

  • I found my mistake, maybe it was a too long day :D

    For everyone who has the same kind of this error maybe this helps him to find the wrong code in the application.

    So I implemented a function in my AuthenticationService to check if the user is logged in. This function gets called on every ngOnInit Method. In this method I was calling the Amplify.getCurrentUser() method without waiting for it. So the error was never caught by the method and it throws after initializing my application.

    Wrong code:

    async isSignedIn(): Promise<boolean> {
        try {
          getCurrentUser();
          this.isLoggedInSubject.next(true);
        } catch (err) {
          this.isLoggedInSubject.next(false)
          return false;
        }
        return true;
      }
    

    Right way to do it:

    async isSignedIn(): Promise<boolean> {
        try {
          await fetchAuthSession({ forceRefresh: true }); // try to refresh the session first
          await getCurrentUser(); // Wait for getCurrentUser, if not logged in an exception will be thrown
          this.isLoggedInSubject.next(true);
        } catch (err) {
          this.isLoggedInSubject.next(false)
          return false;
        }
        return true;
      }