aws-amplify / amplify-js

A declarative JavaScript library for application development using cloud services.
https://docs.amplify.aws/lib/q/platform/js
Apache License 2.0
9.42k stars 2.13k forks source link

Amplify with Ionic and Social Login on Android (Federated) with Cognito pools #5351

Closed togro closed 10 months ago

togro commented 4 years ago

Which Category is your question related to?

Auth

What AWS Services are you utilizing?

Cognito, AWS AppSync, Analytics , S3

Provide additional details e.g. code snippets

Hi

We have a app with amplify and ionic ( 5.4.9, below more info) . All works fine , s3, auth , analitycs , admin queries , auth .

But with auth and Federated Social Login we have problems with Android , on Web works fine.

We singup with Google Federated HostedUI on Cognito pools and auth works fine, but when can back to us we capture with deeplinks , and deeplinks trigger ok .

On next step when redirect from deeplinks to page for use , amplify detect SignIn with “A user Google_103030042694745594198 has been signed in” , that is ok.

But after that give us a error like this :

Failed to execute ‘replaceState’ on ‘History’: A history state object with URL 'com.movilgate.awslogin://app/auth/signin/'

We have an exception in this step and call Auth.currentAuthenticatedUser() , but we don’t know if that is ok , and is very ugly method .

Exists any example o technique for this works fine on android ?

ionic info :

Ionic:

Ionic CLI : 5.4.9 (/Users/mtoro/.ionic/Studio/Tools/lib/node_modules/ionic) Ionic Framework : @ionic/angular 5.0.7 @angular-devkit/build-angular : 0.803.26 @angular-devkit/schematics : 8.3.26 @angular/cli : 8.3.26 @ionic/angular-toolkit : 2.2.0

Cordova:

Cordova CLI : 9.0.3 (cordova-lib@9.0.2) Cordova Platforms : android 8.1.0 Cordova Plugins : cordova-plugin-ionic-keyboard 2.2.0, cordova-plugin-ionic-webview 4.1.3, (and 5 other plugins)

Utility:

cordova-res : 0.6.0 (update available: 0.11.0) native-run : 0.2.8 (update available: 1.0.0)

System:

NodeJS : v12.16.1 (/Users/mtoro/.nvm/versions/node/v12.16.1/bin/node) npm : 6.13.4 OS : macOS Catalina Xcode : Xcode 11.3.1 Build version 11C504

mlabieniec commented 4 years ago

@togro this could potentially be an angular / routing lifecycle issue. It could be related to redirecting to soon. Where/when are you redirecting in the app lifecycle? You might need to do this on something like afterViewInit or later with deep linking. Another way to validate this is the issue is to put your redirect in a setTimeout, or you could use ngZone, give just sticking a setTimeout in there to see if this is the issue.

setTimeout(() => { this.router.navigate(['/somewhere']); });

Although when I look at the error, it looks like it's trying to replace the html5 push state with a deep link e.g. 'com.movilgate.awslogin://app/auth/signin/' are you setting the router.navigate somewhere to goto in your app, or is this happening before you can do that?

togro commented 4 years ago

@mlabieniec I try , but deeplinks, only works on main.ts .

I try to put deeplinks on login.ts on AfterViewInit , but is no triggering .

And with router.navigate does'nt works, only with document.location.href .

I read and investigate a lot, but not found any example with android/ionic. + deeplinks + social login with cognito

I think you are right about life cycle , is something with lifecycle and the premature call .

This is the code for main.ts , after that go to login.ts where is hub from amplify and detect well SigIn on google, but after that gave that error on history.

import { Component, NgZone } from '@angular/core';

import { Platform } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { AmplifyService } from 'aws-amplify-angular';
import { Router } from '@angular/router';
import { EventBusService } from './_services/event-bus.service';
import { Deeplinks } from '@ionic-native/deeplinks/ngx';
@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss']
})
export class AppComponent {
  authState: any;

  constructor(
    private platform: Platform,
    private router: Router,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    public amplify: AmplifyService,
    private eventBusService: EventBusService,
    private deeplinks: Deeplinks,
    private zone: NgZone,
  ) {
    this.eventBusService.on('data:AuthState', (data: any) => {
      console.log('eventBusService', data);
    });
    this.eventBusService.on('initializeApp', (data: any) => {
      console.log('initializeApp', data);
      this.initializeApp();
    });

    this.initializeApp();
  }

  initializeApp() {

    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();

      this.deeplinks.route({
        '/auth/signin/': {},
        '/auth/signout/': {},
      }).subscribe(match => {
        // match.$route - the route we matched, which is the matched entry from the arguments to route()
        // match.$args - the args passed in the link
        // match.$link - the full link data
        this.zone.run(() => {
            console.log("DeepLinks OK !:", match);

            document.location.href = `http://localhost/login/?code=${match.$args.code}&state=${match.$args.state}`;
            // setTimeout(() => {
            //   document.location.href = `http://localhost/login/?code=${match.$args.code}&state=${match.$args.state}`;
            // },100);
            // setTimeout(() => {
            //                   this.router.navigate(['/login'], { queryParams: { code: match.$args.code, state: match.$args.state}});;
            //                 });
            console.log('Successfully matched route', match);
        });
      }, nomatch => {
        // nomatch.$link - the full link data
        console.error('Got a deeplink that didn\'t match', nomatch);
      });

      // amplify
      this.authState = {loggedIn: false};
      this.amplify.authStateChange$
              .subscribe(authState => {
                console.log('ZZZZ:', authState);
                this.authState.loggedIn = authState.state === 'signedIn';
                this.eventBusService.emit({name: 'data:AuthState', value: this.authState});
                console.log('XXX:', this.authState);
                // if ( authState.user  )
                if ( this.authState.loggedIn === true) {
                    // portada
                    console.log('Redir !!!');
                    // Analytics.enable();
                    this.router.navigateByUrl('/portada');
                }
                this.statusBar.styleDefault();
                this.splashScreen.hide();
              });
    });
  }
}
togro commented 4 years ago

Any update about Social Login on Android with ionic ?

oliverandersencox commented 4 years ago

This is a 6 month long pain for me. Are there seriously no fixes for something that is supposed to be integrated (Ionic)!!

oliverandersencox commented 4 years ago

However could @sammartinez please comment on why the hub - after a successful social Ionic login - first emits sign in success but immediately after will emit a sign in failure

oliverandersencox commented 4 years ago

@togro so my approach is fairly similar to yours, however I am using capacitor (highly recommend) which has deep links out the box, however the approach taken for that is very similar.

So after triggering the reload of the application - I still get exactly the same error as you however this doesnt actually effect the next step (this may be useful - but I havent tried myself - https://stackoverflow.com/questions/49365057/angular-deployment-without-server-error-securityerror-failed-to-execute-rep)

Now in your auth service make sure you have the hub listener - mine is in the constructor:

    Hub.listen("auth", async (data: any) => {
      console.log('==============================================')
      console.log('HUB EVENT EMITTED');
      switch (data.payload.event) {
        case "signIn":

          setTimeout(() => {
            console.log("SIGN IN - DATA BELOW");
            console.log(data);
            this.zone.run(() => {
              this.setAuthstate(true);
              this.initUser(data?.payload?.data)
            })

          })
          break;
        case "signIn_failure":
          console.log("SIGN IN FAILURE");
          break;
        case "signOut":
          console.log("SIGN  out");
          break;
        case "customOAuthState":
          console.log('CUSTOM OAUTH')
          break;
        default:
          break;
      }
    });

Now, it will log the sign in, but also the failure - this is clearly an amplify issue - so within the success if you add a function to initilaise the user:

 private async initUser(authState: any) {
    const lastCleanRefresh: moment.Moment = moment(await this.utils.getItem('ping-clean-refresh'));
    let stream: Observable<IUser>;
    if (!lastCleanRefresh || (moment().diff(lastCleanRefresh, 'hours') > 42)) {
      console.log('USER REFRESH REQUIRED');
      stream = this.user.refreshUserData(authState?.user?.username || authState?.username);
    } else {
      console.log('NO USER REFRESH REQUIRED')
      stream = this.user.fetchUser(authState?.user?.username || authState?.username);

    }
}

When I call this, because there is actually a successful login, the application will fetch your user data and the app should be all good.

I think this may help with the auth error as well (yet to test) - https://github.com/aws-amplify/amplify-js/issues/5959

oliverandersencox commented 4 years ago

@togro I now have ti fully working without your error.

My redirect URL is - capacitor://localhost/welcome/ as I am using capacitor

I also opted to use the capactior in app broswer so as to not navigate away from the application as Apple rejected mine for that.

to do that I do this for the Facebook login:

  public async loginWithFacebook(): Promise<any> {
    this.zone.run(async () => {
      const base: string = 'https://MYAPP-prod.auth.eu-west-1.amazoncognito.com/oauth2/authorize?';
      const redirect_url: string = 'capacitor://localhost/welcome/&'
      const type: string = 'response_type=code&';
      const client: string = 'client_id=CLIENTIDHERE&state=STATE&';
      const scope: string = 'scope=aws.cognito.signin.user.admin+email+openid+phone+profile&';
      const provider: string = 'identity_provider=Facebook';
      const url = base + redirect_url + type + client + scope + provider;
      if (this.platform.is('capacitor')) {
        const result = await this.utils.openBrowser(url, false);
      } else {
        this.amplify.auth().federatedSignIn({ provider: 'Facebook' });
      }
    })
  }

which opens the browser in a modal. Then once the reload has finished I have to manually close the browser or it will stay up.

Then on the reload the capacitor deep links take hold:

App.addListener('appUrlOpen', async (data: any) => {
      console.log(data.url);
      try {
        await Browser.close();
      } catch (err) {
        console.error(err);
      }
      this.deeplinks.consumeDynamicLink(data.url);
    });

The browser close there (bit hacky) but does the job, and passes the url that opened the app to the routing service:

try {
          console.log('AUTH RELOAD TRIGGEED')
          const reloadURL = this.platform.is('ios') ? environment.redirectUrls.ios : environment.redirectUrls.android;
          console.log(reloadURL)
          document.location.href = `${reloadURL}?code=${queryParams.code}&state=${queryParams.state}`;
          return;
        } catch (err) {
          this.logger.logError(err);
        }

From here the Hub takes over and all seems to work well. Hope that helps!

oliverandersencox commented 4 years ago

@togro even better, now the error message you were having has been resolved for me, the hub is no longer needed and the amplify auth state subscriber works as it should do!

togro commented 3 years ago

@sammartinez ... Any working example with Ionic + Android for social login with last versions ?

amhinson commented 3 years ago

@togro Did the solution presented above work for you? Just let me know 👍 Also, would you be able to open a feature request on the docs repo for adding an example?

togro commented 3 years ago

I am using it with cordova, not capacitor, I checked last month and it doesn't work.

I appreciate any working example, I see that the process works fine, but it always fails in:

Failed to execute ‘replaceState’ on ‘History’

@amhinson @sammartinez

oliverandersencox commented 3 years ago

@sammartinez this issue with ionic has been going on for years now. There are example for react but nothing to help with angular ionic, and now out of nowhere my hacky way has stopped working.

I see this has been added where we can define a function to deal with the auth on devices however this doesnt work with ionic:

async function urlOpener(url, redirectUrl) {
    const { type, url: newUrl } = await WebBrowser.openAuthSessionAsync(
        url,
        redirectUrl
    );

    if (type === 'success' && Platform.OS === 'ios') {
        WebBrowser.dismissBrowser();
        return Linking.openURL(newUrl);
    }
}

Amplify.configure({
    ...awsconfig,
    oauth: {
        ...awsconfig.oauth,
        urlOpener,
    },
});

Can you guys help direct us as to how to do this is angular as there are no docs anywhere for it

togro commented 3 years ago

There is no other option in which we can invoke another plugin to make the social login and then invoke a lambda that updates cognito and returns a token that is passed to some Auth function of Amplify and the state is updated and we can continue with the authenticated flow ?

oliverandersencox commented 3 years ago

@sammartinez..........

sammartinez commented 3 years ago

Apologizes for the delay on this, we are looking into this issue and will provide an update on the functionality next week on this. Need to take the time to produce what you are running into. For some clarity for us, what documentation are you following for our Ionic integration? Also, can please provide your package.json along with your environment settings?

Please use the follow command:

npx envinfo --system --binaries --browsers --npmPackages --npmGlobalPackages

Thanks ahead of time!

oliverandersencox commented 3 years ago

thanks @sammartinez

The ionic components are great but really aren't flexible enough to build into a custom app (in my opinion).

The main problem is the authentication system redirection.

  1. When using the federated login functions it opens the safari app to do the authentication, which will guarantee rejection in the app store - meaning its a no go.
  2. When using the capacitor in app browser the only option I've found is to create a custom auth endpoint from - 'eu-west-1.amazoncognito.com/oauth2/authorize', which works nicely and does in fact redirect correctly within the app itself. The next step however is to detect the authentication in the app which requires a document.location.href - with the code and state passed in. However given that Ios and anroid run on different hosts capacitor and localhost, it means the redirect url has t be the same, which was problematic but workable. I was unable to get ios to detect auth using any other redirect url which doesn't start with capacitor.

Which brings me onto the other question I asked above - I noticed for the react docs this problem has been solved with this code (i think):

Amplify.configure({
    ...awsconfig,
    oauth: {
        ...awsconfig.oauth,
        urlOpener,
    },
});

Which from what I can tell means you can pre define the in app browser dealing with the federated authentication. However I tried various ways of trying to do this but capacitors browser does not behave in a way which makes this viable, and the main.ts file deals with the config set up and I can attach this functionality until the angular app has loaded - unless you have some guidance here.

It would be great of you are able to give some guidance on how we can makes this auth process fit the above, as it has been a very trial and error approach getting this working and we are now in production.

System: OS: macOS 10.15.7 CPU: (12) x64 Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz Memory: 147.07 MB / 16.00 GB Shell: 3.2.57 - /bin/bash Binaries: Node: 14.0.0 - /usr/local/bin/node Yarn: 1.22.10 - ~/Documents/Development/Ping/Ping-App/node_modules/.bin/yarn npm: 6.14.9 - ~/Documents/Development/Ping/Ping-App/node_modules/.bin/npm Browsers: Chrome: 87.0.4280.88 Firefox: 83.0 Safari: 14.0 npmPackages: @angular-devkit/architect: ^0.803.29 => 0.803.29 @angular-devkit/build-angular: ^0.901.12 => 0.901.12 @angular-devkit/core: ^9.1.12 => 9.1.12 @angular-devkit/schematics: ^9.1.12 => 9.1.12 @angular/animations: ^9.1.12 => 9.1.12 @angular/cdk: ~7.3.7 => 7.3.7 @angular/cli: ^9.1.12 => 9.1.12 @angular/common: ^9.1.12 => 9.1.12 @angular/compiler: ^9.1.12 => 9.1.12 @angular/compiler-cli: ^9.1.12 => 9.1.12 @angular/core: ^9.1.12 => 9.1.12 @angular/forms: ^9.1.12 => 9.1.12 @angular/language-service: ^9.1.12 => 9.1.12 @angular/platform-browser: ^9.1.12 => 9.1.12 @angular/platform-browser-dynamic: ^9.1.12 => 9.1.12 @angular/pwa: ^0.12.4 => 0.12.4 @angular/router: ^9.1.12 => 9.1.12 @angular/service-worker: ^9.1.12 => 9.1.12 @aws-amplify/ui: ^1.2.3 => 1.2.3 @aws-amplify/ui-angular: ^0.2.15 => 0.2.15 @capacitor/android: ^2.4.3 => 2.4.4 @capacitor/cli: ^2.4.3 => 2.4.4 @capacitor/core: ^2.4.3 => 2.4.4 @capacitor/ios: ^2.4.3 => 2.4.4 @fortawesome/angular-fontawesome: ^0.3.0 => 0.3.0 @fortawesome/fontawesome-pro: ^5.15.1 => 5.15.1 @fortawesome/fontawesome-svg-core: ^1.2.32 => 1.2.32 @fortawesome/free-brands-svg-icons: ^5.15.1 => 5.15.1 @fortawesome/free-regular-svg-icons: ^5.15.1 => 5.15.1 @fortawesome/free-solid-svg-icons: ^5.15.1 => 5.15.1 @fortawesome/pro-duotone-svg-icons: ^5.15.1 => 5.15.1 @fortawesome/pro-light-svg-icons: ^5.15.1 => 5.15.1 @fortawesome/pro-regular-svg-icons: ^5.15.1 => 5.15.1 @ionic-native/barcode-scanner: ^5.30.0 => 5.30.0 @ionic-native/calendar: ^5.30.0 => 5.30.0 @ionic-native/call-number: ^5.30.0 => 5.30.0 @ionic-native/core: ^5.30.0 => 5.30.0 @ionic-native/email-composer: ^5.30.0 => 5.30.0 @ionic-native/file: ^5.30.0 => 5.30.0 @ionic-native/in-app-browser: ^5.30.0 => 5.30.0 @ionic-native/ionic-webview: ^5.30.0 => 5.30.0 @ionic-native/native-geocoder: ^5.30.0 => 5.30.0 @ionic-native/open-native-settings: ^5.30.0 => 5.30.0 @ionic-native/sms: ^5.30.0 => 5.30.0 @ionic-native/social-sharing: ^5.30.0 => 5.30.0 @ionic/angular: ^5.5.2 => 5.5.2 @ionic/angular-toolkit: ^2.3.3 => 2.3.3 @ionic/pwa-elements: ^1.5.2 => 1.5.2 @ngx-translate/core: ^11.0.1 => 11.0.1 @ngx-translate/http-loader: ^4.0.0 => 4.0.0 @types/googlemaps: ^3.40.5 => 3.40.5 @types/graphql: ^14.5.0 => 14.5.0 @types/hammerjs: ^2.0.36 => 2.0.36 @types/jasmine: ^2.8.17 => 2.8.17 @types/jasminewd2: ^2.0.8 => 2.0.8 @types/mapbox-gl: ^0.51.12 => 0.51.12 @types/node: ^10.17.48 => 10.17.48 add: ^2.0.6 => 2.0.6 aws-amplify: ^3.3.9 => 3.3.12 aws-amplify-angular: ^5.0.38 => 5.0.41 bootstrap: ^4.5.3 => 4.5.3 browserslist: ^4.16.0 => 4.16.0 call-number: ^1.0.1 => 1.0.1 canvas-confetti: ^1.3.2 => 1.3.2 codelyzer: ^5.2.2 => 5.2.2 color: ^3.1.3 => 3.1.3 cordova-open-native-settings: ^1.5.2 => 1.5.2 cordova-plugin-calendar: ^5.1.5 => 5.1.5 cordova-plugin-device-motion: ^2.0.1 => 2.0.1 cordova-plugin-email-composer: ^0.9.2 => 0.9.2 cordova-plugin-file: ^6.0.2 => 6.0.2 cordova-plugin-inappbrowser: ^4.1.0 => 4.1.0 cordova-plugin-nativegeocoder: ^3.4.1 => 3.4.1 cordova-plugin-x-socialsharing: ^5.6.8 => 5.6.8 cordova-res: ^0.15.2 => 0.15.2 cordova-sms-plugin: ^1.0.0 => 1.0.0 cordova-support-android-plugin: ^1.0.2 => 1.0.2 cordova-support-google-services: ^1.4.1 => 1.4.1 core-js: ^2.6.12 => 2.6.12 es6-promise-plugin: ^4.2.2 => 4.2.2 hammerjs: ^2.0.8 => 2.0.8 ionic-image-loader: ^7.0.0-beta.2 => 7.0.0-beta.2 ionic-image-loader-v5: ^1.0.2 => 1.0.2 jasmine-core: ~2.99.1 => 2.99.1 jasmine-spec-reporter: ~4.2.1 => 4.2.1 jetifier: ^1.6.6 => 1.6.6 karma: ~3.1.4 => 3.1.4 karma-chrome-launcher: ~2.2.0 => 2.2.0 karma-coverage-istanbul-reporter: ^2.1.1 => 2.1.1 karma-jasmine: ~1.1.2 => 1.1.2 karma-jasmine-html-reporter: ^0.2.2 => 0.2.2 mapbox-gl: ^0.54.1 => 0.54.1 moment: 2.24.0 => 2.24.0 ngx-embed-video: ^1.0.4 => 1.0.4 ngx-mapbox-gl: ^3.3.1 => 3.3.1 ngx-moment: ^3.5.0 => 3.5.0 node-vibrant: ^3.1.4 => 3.1.6 npm: ^6.14.9 => 6.14.9 observable-profiler: ^0.1.1 => 0.1.1 phonegap-plugin-barcodescanner: ^8.1.0 => 8.1.0 protractor: ^5.4.4 => 5.4.4 robust-point-in-polygon: ^1.0.3 => 1.0.3 rxjs: ^6.6.3 => 6.6.3 ts-node: ~8.0.0 => 8.0.3 tslint: ~5.12.0 => 5.12.1 typescript: ~3.8.3 => 3.8.3 web-animations-js: ^2.3.2 => 2.3.2 yarn: ^1.22.10 => 1.22.10 zone.js: ~0.10.3 => 0.10.3 npmGlobalPackages: @angular/cli: 10.2.0 @aws-amplify/cli: 4.29.0 @ionic/cli: 6.12.3 capacitor-resources: 2.0.3 cordova-res: 0.15.1 firebase-tools: 9.0.1 ngx-unused-css: 2.1.0 npm: 6.14.6 ping-lib: 0.0.1 serverless: 2.8.0

amhinson commented 3 years ago

@oliverandersencox Just curious, what are you using for the redirect signin and signout URIs?

You are also correct in the intended use for urlOpener. Ideally you would be able to add in your custom logic for using the Capacitor in-app browser here, but perhaps there is a gap. If possible, it'd be great to know what you've tried that wasn't successful in hopes that we can find a solution.

oliverandersencox commented 3 years ago

@amhinson I tried using 'app.ping.com' which stopped working last week out of nowhere, but now im forced to use capacitor://welcome as it seems when the window reload url does not contain this, amplify doesn't authenticate.

And RE the urlOpener, I dont understand how I can attach this, as we can't do it in the main.ts file as the app has not loaded capacitor by that point, so I'm wondering if there is a way to set this urlOpener function after the app has initialise.

shekhartupe commented 3 years ago

Just posted a reference working implementation notes at - https://github.com/aws-amplify/amplify-js/issues/3537

angusho1 commented 3 years ago

@oliverandersencox Do you have any updates on your approach to the social login implementation?

angusho1 commented 3 years ago

@sid19928 How does your deep link have 'access_token', 'id_token', etc. as params? As far as I know, the callback URL after signing in only contains 'code' and 'state' as params.

sid19928 commented 3 years ago

@angusho1 if your responseType is 'token' in the config file aws-exports.ts then you get access_token and id_token etc as params.

angusho1 commented 3 years ago

@sid19928 Thanks for the clarification. I have a question about this step:

  1. After storing data in localStorage you can initiate the login process which is implemented in the same way as the normal sign in of Cognito in the web app.

What do you mean by 'initiate the login process'? Are you saying that we should call Auth.signIn using the user attributes in local storage?

sid19928 commented 3 years ago

@angusho1 you have already called Auth.federatedSignIn() for redirecting to social provider then after successfull login from there you don't have to call Auth.signIn(). You need to use user data and token for accessing the apis of cognito and perform further actions according to your requirements. I would suggest that you go through aws cognito docs to understand the flow. Basically for mobile we are doing the localStorage part manually which is done by aws amplify in case of web implementation. Deep linking is used to send the tokens generated to our mobile app.

angusho1 commented 3 years ago

You need to use user data and token for accessing the apis of cognito and perform further actions according to your requirements.

Can you give an example of what 'further actions' might entail? Part of what needs to happen in this step is we need to trigger an event in the Amplify Hub's auth channel, right? And if that is done through a Cognito API, what kind of endpoint would I use?

dineshPULSY commented 1 year ago

@togro I now have ti fully working without your error.

My redirect URL is - capacitor://localhost/welcome/ as I am using capacitor

I also opted to use the capactior in app broswer so as to not navigate away from the application as Apple rejected mine for that.

to do that I do this for the Facebook login:

  public async loginWithFacebook(): Promise<any> {
    this.zone.run(async () => {
      const base: string = 'https://MYAPP-prod.auth.eu-west-1.amazoncognito.com/oauth2/authorize?';
      const redirect_url: string = 'capacitor://localhost/welcome/&'
      const type: string = 'response_type=code&';
      const client: string = 'client_id=CLIENTIDHERE&state=STATE&';
      const scope: string = 'scope=aws.cognito.signin.user.admin+email+openid+phone+profile&';
      const provider: string = 'identity_provider=Facebook';
      const url = base + redirect_url + type + client + scope + provider;
      if (this.platform.is('capacitor')) {
        const result = await this.utils.openBrowser(url, false);
      } else {
        this.amplify.auth().federatedSignIn({ provider: 'Facebook' });
      }
    })
  }

which opens the browser in a modal. Then once the reload has finished I have to manually close the browser or it will stay up.

Then on the reload the capacitor deep links take hold:

App.addListener('appUrlOpen', async (data: any) => {
      console.log(data.url);
      try {
        await Browser.close();
      } catch (err) {
        console.error(err);
      }
      this.deeplinks.consumeDynamicLink(data.url);
    });

The browser close there (bit hacky) but does the job, and passes the url that opened the app to the routing service:

try {
          console.log('AUTH RELOAD TRIGGEED')
          const reloadURL = this.platform.is('ios') ? environment.redirectUrls.ios : environment.redirectUrls.android;
          console.log(reloadURL)
          document.location.href = `${reloadURL}?code=${queryParams.code}&state=${queryParams.state}`;
          return;
        } catch (err) {
          this.logger.logError(err);
        }

From here the Hub takes over and all seems to work well. Hope that helps!

Hello I am new and i am using ionic react. Any idea how to implement this solution to ionic react. I have tried everything and my Hub is not listening or returning anything. Thank you

nadetastic commented 11 months ago

Looks related to https://github.com/aws-amplify/amplify-js/issues/5959 https://github.com/aws-amplify/amplify-js/issues/3537 https://github.com/aws-amplify/amplify-js/issues/12506

keygun-development commented 11 months ago

@nadetastic thank you for mentioning my issue. It has been resolved see my answer: https://github.com/aws-amplify/amplify-js/issues/3537#issuecomment-1805360225

nadetastic commented 10 months ago

Closing this issue in favor of #3537