Amplify authentication with angular: error retrieving currentUserInfo

Viewed 12

I am having an issue, when I trying to get the user info, iam getting null in my method isAuthenticated in the instruction Auth.currentUserInfo(); and user not signed, when I try with Auth.currentAuthenticatedUser(). I have searched for different solutions but I had not could fix the problem.

I leave some of my code. I hope somebody could help me:

My app.module amplyfy configuration is

Amplify.configure({
  Auth: {
    mandatorySignIn: false,
    region: amplifyConfig.cognito.REGION,
    userPoolId: amplifyConfig.cognito.USER_POOL_ID,
    userPoolWebClientId: amplifyConfig.cognito.APP_CLIENT_ID,
    oauth: {
      domain: amplifyConfig.cognito.DOMAIN,
      scope: amplifyConfig.cognito.SCOPE,
      responseType: amplifyConfig.cognito.RESPONSE_TYPE
    }
  }
});

my dependencys in package.json are:

"@aws-amplify/api": "^4.0.45",
"@aws-amplify/auth": "^4.5.9",
"@aws-amplify/pubsub": "^4.4.6",
"aws-amplify": "^3.4.3",
"aws-amplify-angular": "^6.0.26",

and my cognito service is:

import { Injectable } from '@angular/core';
import { Auth } from "aws-amplify";
import { BehaviorSubject } from 'rxjs';

export interface IUser {
  userName: string;
  password: string;
}

@Injectable({
  providedIn: 'root'
})
export class CognitoService {

  authenticationSubject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);

  constructor() {
    this.isAuthenticated().then(r => {this.authenticationSubject.next(r)});
  }

  public signUp(user: IUser): Promise<any> {
    return Auth.signUp({
      username: user.userName,
      password: user.password,
    });
  }

  public confirmSignUp(user: IUser): Promise<any> {
    return Auth.confirmSignUp(user.userName, '');
  }

  public async signIn(user: IUser, rememberUser: boolean): Promise<boolean> {
    try {
      await Auth.signIn(user.userName, user.password);
      this.authenticationSubject.next(true);
      return true;
    } catch (error) {
      console.log('error signing in', error);
      this.authenticationSubject.next(true);
      return false;
    }
  }

  public async signOut(): Promise<any> {
    try {
      await Auth.signOut();
      this.authenticationSubject.next(false);
    } catch (error) {
      console.log('error signing out: ', error);
    }
  }

  private async isAuthenticated(): Promise<boolean> {
    try {
      let user = await Auth.currentUserInfo();
      return !!user;
    } catch (error) {
      return false;
    }
  }

  public async getUser(): Promise<any> {
    return await Auth.currentUserPoolUser();
  }

  public updateUser(user: IUser): Promise<any> {
    return Auth.currentUserPoolUser().then((cognitoUser: any) => {
      return Auth.updateUserAttributes(cognitoUser, user);
    });
  }
}

thanks for your help

0 Answers
Related