Yann
Yann

Reputation: 1

amazon-cognito-identity-js login returns null session and doesn't store token in localStorage in Angular application

I'm working on implementing user authentication in my Angular application using AWS Cognito. While the sign-up process works without errors, I'm running into an issue where the session is not properly initialized, resulting in the following error when attempting to change the password.

Cognito service :

import { Injectable } from '@angular/core';
import { Amplify } from 'aws-amplify';
import { environment } from '../../environments/environment';
import { AuthenticationDetails, CognitoUser, CognitoUserAttribute, CognitoUserPool, ISignUpResult } from 'amazon-cognito-identity-js';
import {Router} from '@angular/router';
@Injectable({
  providedIn: 'root'
})
export class CognitoService {

  userPool: CognitoUserPool ;
  cognitoUser: CognitoUser | null = null;

  constructor(private router: Router) {

    this.userPool = new CognitoUserPool({
      UserPoolId: environment.cognito.userPoolId,
      ClientId: environment.cognito.clientId,
      Storage: window.localStorage
    });

   }


   async login(email: string, password: string): Promise<any> {
    const authenticationDetails = new AuthenticationDetails({
        Username: email,
        Password: password
    });

    const userData = {
        Username: email,
        Pool: this.userPool
    };

    try {
        this.cognitoUser = new CognitoUser(userData);

        return new Promise((resolve, reject) => {
            this.cognitoUser?.authenticateUser(authenticationDetails, {
                onSuccess: (result) => {
                    console.log('Access token:', result.getAccessToken().getJwtToken());
                    console.log('ID token:', result.getIdToken().getJwtToken());
                    console.log('Refresh token:', result.getRefreshToken().getToken());

                    // Forcer le stockage de la session utilisateur
                    if (this.cognitoUser) {
                        this.cognitoUser.setSignInUserSession(result);
                        console.log('Session manually set:', this.cognitoUser.getSignInUserSession());
                    }

                    this.router.navigate(['/home']);
                    resolve(result);
                },
                onFailure: (err) => {
                    console.error('Authentication failed:', err);
                    reject(err);
                },
                newPasswordRequired: (userAttributes, requiredAttributes) => {
                    console.log('New password required', userAttributes, requiredAttributes);
                    this.router.navigate(["/newPasswordRequire"], {
                        queryParams: {
                            email: userAttributes.email,
                            email_verified: userAttributes.email_verified
                        }
                    });
                    resolve({ userAttributes, requiredAttributes, cognitoUser: this.cognitoUser });
                }
            });
        });

    } catch (error) {
        console.error('Failed to create CognitoUser object.', error);
        throw new Error('Failed to create CognitoUser object.');
    }
}


signUp(email: string, password: string, attributes: { [key: string]: string }): Promise<ISignUpResult | undefined> {
  const attributeList: CognitoUserAttribute[] = [];

  for (const key in attributes) {
    if (attributes.hasOwnProperty(key)) {
      attributeList.push(new CognitoUserAttribute({
        Name: key,
        Value: attributes[key]
      }));
    }
  }

  return new Promise((resolve, reject) => {
    this.userPool.signUp(email, password, [], [], (err, result) => {
        if (err) {
            console.error('Sign up error:', err);
            reject(err);
        } else {
          console.log('Sign up result:', result);
        }
    });
});
}




  async changePassword(oldPassword: string, newPassword: string, confirmPassword: string): Promise<void> {

    this.cognitoUser?.getSession((err: any, session: any) => {
      if (err) {
          console.error('Error getting session:', err);
          return;
      }
      console.log('Session:', session);
      if (session && session.isValid()) {
          console.log('Session is valid.');
      } else {
          console.log('Session is invalid or null.');
      }
  });

    if (newPassword !== confirmPassword) {
        console.error('Passwords do not match.');
        alert('Les mots de passe ne correspondent pas.');
        return;
    }


  }

Login Component :

import { Component } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { signUp  } from '@aws-amplify/auth';
import { CognitoService } from '../../_services/cognito.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-login',
  standalone: false,
  // imports: [],
  templateUrl: './login.component.html',
  styleUrl: './login.component.css'
})
export class LoginComponent {

  constructor(private fb: FormBuilder,
    private router: Router,
    private cognitoService: CognitoService ) {


     }

  loginForm = this.fb.group({
      email: ['', [Validators.required, Validators.email] ],
      password: ['', [Validators.required, Validators.minLength(8)]]
  });

  ngOnInit(): void {}

  async onSubmit(): Promise<void> {
    if (this.loginForm.valid) {
      const { email, password } = this.loginForm.value;
      try {
        const user = await this.cognitoService.login(email ?? '', password ?? '');
        console.log('Sign in successful', user);
      } catch (error) {
        console.error('Error signing in', error);
      }
    }
  }

  get email() {
    return this.loginForm.controls['email'];
  }

  get password() {
    return this.loginForm.controls['password'];
  }

}

The Problem

Despite the code running without throwing errors during the sign-up process, I encounter the following issues:

Session is null: After a successful sign-up, when trying to use the session (e.g., during a password change), the session remains null.

ID Token not stored in localStorage: The authentication tokens (ID token, Access token, Refresh token) are not being saved in localStorage, even though I've configured Cognito to use localStorage.

The Question

Why might the session (signInUserSession) be null and the authentication tokens not be stored in localStorage after a successful sign-up? How can I ensure the session is properly initialized and the tokens are correctly stored after registration?

Any insights or suggestions would be greatly appreciated.

Thank you!

Upvotes: 0

Views: 51

Answers (0)

Related Questions