Utilize Ionic Auth Connect to establish the currentSession and currentAuthenticatedUser on AWS Amplify

Problem with Amplify Configuration

In the process of developing a new ionic app, our team decided to utilize AWS Amplify as our backend solution. To interact effectively with various services, we opted to use both "AMAZON_COGNITO_USER_POOLS" and "API_KEY" authentication types.

  • We incorporated Amplify API to connect with API Gateway for seamless data interaction.
  • Additionally, we integrated a GraphQL API with codegen for structured data management.

Our chosen method for authentication involved integrating Ionic Auth Connect with Cognito hosted UI. Despite following the documentation closely, we encountered issues with user recognition within Amplify.

Upon reviewing the resources available through Amplify and auth connect docs, we were unable to find a straightforward solution to manually set the current user session.

A few attempts were made to manually configure tokens using Amplify.configure and implementing an auth interceptor. However, these efforts proved unsuccessful due to validation logic embedded within the SDK that hindered our requests.

At this juncture, we are seeking advice on how to establish a user session in Amplify without having to resort to manual construction of API and GraphQL calls.

Answer №1

If you have set up your authentication class as shown below: Check out the official documentation

import { Injectable, NgZone } from '@angular/core';
import { IonicAuth } from '@ionic-enterprise/auth';
import { Platform } from '@ionic/angular';
import { BehaviorSubject, Observable } from 'rxjs';
import { nativeIonicAuthOptions, webIonicAuthOptions } from '../../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class AuthenticationService extends IonicAuth {
  private authenticationChange: BehaviorSubject<boolean> = new BehaviorSubject(false);
  public authenticationChange$: Observable<boolean>;

  constructor(platform: Platform, private ngZone: NgZone) {
    super(platform.is('hybrid') ? nativeIonicAuthOptions : webIonicAuthOptions);
    this.authenticationChange$ = this.authenticationChange.asObservable();
    this.isAuthenticated().then((authenticated) => { this.onAuthChange(authenticated); });
  }

  public async onLoginSuccess(): Promise<void> {
    this.onAuthChange(true);
  }

  public async onLogout(): Promise<void> {
    this.onAuthChange(false);
  }

  private async onAuthChange(isAuthenticated: boolean): Promise<void> {
    this.ngZone.run(() => {
      this.authenticationChange.next(isAuthenticated);
    });
  }
}

You can utilize amazon-cognito-identity-js and manually configure CognitoUserSession like this:

Install amazon-cognito-identity-js

Create a method to handle setting the user session:

  private async setAmplifyUser(): Promise<void> {
    const idToken = await this.getIdToken();
    const accessToken = await this.getAccessToken();
    const authResponse = await this.getAuthResponse();
    const refreshToken = await this.getRefreshToken();

    const userPool = new CognitoUserPool({
      UserPoolId: `YOUR_USER_POOL_ID `,
      ClientId: `YOUR_APP_CLIENT_ID `,
    });

    // Continue with setting the user session...
  }

To ensure that Cognito session stays in sync with auth connect's session, make sure to call setAmplifyUser within onAuthChange

You can validate if your session is properly set by calling these methods:

Auth.currentAuthenticatedUser().then((res) => {
  console.log('currentAuthenticatedUser', res);
});

Auth.currentSession().then((res) => {
  console.log('currentSession', res);
});

Note when using multiple authentication modes: subscribe to onAuthChange in AppModule's constructor and switch aws_appsync_authenticationType based on the authentication state.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging parameters within a sequence of object properties

Within the realm of Angular, I am dealing with interfaces that take on a structure similar to this (please note that this code is not my own): export interface Vehicles { id: number; cars: Car; trucks: Truck; } Export interface Car { make: ...

What are the steps to update data using Angular?

I am currently working on a project to create a simple webpage that allows users to add values to a database. The database only contains an ID and a value, which should also be displayed on the page. Although my code is functioning correctly and I can suc ...

Incorporating an offset with the I18nPluralPipe

Having trouble with my multiselect dropdown and the text pluralization. I attempted to use the I18nPluralPipe, but can't seem to set an offset of 1. ListItem = [Lion, Tiger, Cat, Fox] Select 1 Item(Tiger) = "Tiger", Select 3 Item(Tiger, Cat, Fox) = ...

Fullcalendar in Angular fails to update events automatically

I am exploring the integration of fullcalendar with angular. Despite adding valid events to my events field, they are not displaying in the UI. However, hardcoded events are appearing. I am relatively new to angular, so the issue may not be directly relat ...

How can I utilize Angular services to transfer a count value to the Component?

I've been working on creating a coin counter for my application by developing a service specifically for counting coins. However, when I tried to use this service in one of my components where the count function is triggered, I encountered some diffic ...

`Angular Image Upload: A Comprehensive Guide`

I'm currently facing a challenge while attempting to upload an image using Angular to a Google storage bucket. Interestingly, everything works perfectly with Postman, but I've hit a roadblock with Angular Typescript. Does anyone have any suggesti ...

Exploring Custom Validator Comparisons in Angular

Having trouble comparing two input values in a custom validator. An error should occur if the minValue exceeds the maxValue. FormGroup: sumFormGroup = this.formBuilder.group({ from: ['', [Validators.min(0), sumValidator]], to: [&ap ...

What is the method for extracting user input from a text box on a webpage?

Having trouble with retrieving the value from a text box in my search function. SearchBar Component import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-search', templateUrl: './search.compon ...

The issue with Angular2 Material select dropdown is that it remains open even after being toggled

Exploring the world of Node.js, I am delving into utilizing the dropdown feature from Angular Material. However, an issue arises once the dropdown is opened - it cannot be closed by simply clicking another region of the page. Additionally, the dropdown lis ...

I am experiencing issues with the search feature in angular and node.js that is not functioning properly

Need assistance with debugging this code. I am currently working on adding search functionality to my Angular web page. However, when testing the code in Postman, I keep receiving the message "NO USER FOUND WITH USERNAME: undefined". Additionally, on the w ...

Error: Attempting to access the property 'cinemaName' of an undefined object

I am brand new to using angular2 and higher. My form definition with an input field of type text looks like this: <form class="form-horizontal" name="form" role="form"> <div class="form-group"> <label class="col-md-3 co ...

Navigating through embedded arrays in Angular

JSON Object const users = [{ "name":"Mark", "age":30, "isActive" : true, "cars":{ Owned : ["Ford", "BMW", "Fiat"], Rented : ["Ford", "BMW", "Fiat" ...

Guide on utilizing Subscribe Observable for performing lookup in Angular

I am new to Angular and seeking guidance as my approach may not be the best. Please advise me on a better solution if you have one. My goal is to display a list of records in table format, retrieved from the database where only Foreign Keys IDs are availa ...

Phrases are truncated in the initial line of each ion-item within the ion-list

In Ionic 3, I am facing an issue with my ion-list where the first line inside each ion-item is getting cut off. Specifically, the capital 'A' letter is not entirely visible. Can anyone provide assistance with this? Thank you. Below is my code sn ...

Recording changes in SVG size in Angular 2

I am aiming to create an SVG canvas within an Angular 2 template that automatically scales with its parent element and triggers a redraw method when its size changes. While using the onresize property, I successfully receive events but encounter difficult ...

Tips for verifying the presence of an active session after closing the browser

Here is my situation: When a user logs into the app and then opens another browser window, they are already authenticated thanks to express-session, bypassing the login page. This pattern continues for subsequent browser windows. The issue I am facing no ...

Navigating the bitbucket pipeline to execute test cases for Angular 4 applications

Currently, I am facing an issue while integrating Bitbucket Pipeline for Angular 4. The problem lies in the fact that Chrome browser is not opening in the Bitbucket Pipeline console. My main objective is to figure out a way to execute test cases in the B ...

Retrieve the value of the specific element I have entered in the ngFor loop

I've hit a wall after trying numerous solutions. Here is the code I'm working with: HTML: import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styl ...

Is there a way to run a node script from any location in the command line similar to how Angular's "

Currently, I am developing a node module that performs certain functions. I want to create a command similar to Angular's ng command. However, I am facing compatibility issues with Windows and Linux operating systems. Despite my attempts to modify the ...

Error message in Angular when promises are not defined

Recently, I started working with promises for the first time. I have a function that returns a promise: public DatesGenerator(futercampaign: ICampaign, searchparam: any, i: number): ng.IPromise<any> { return this.$q((resolve, reject) => { ...