How to handle Oauth authentication in Ionic?

Hi,

I’m a beginner in Ionic and would like to ask if Ionic can handle authentication on custom/external web page that uses Oauth (This page is NOT Google, Facebook or other popular sites). If login is successful, it will be redirected to Callback URL. This seems fine on web applications, not sure if it’s possible on mobile app though.

For the mobile app, what I would like to achieve is:

  1. Display the external Login page on mobile screen.
  2. User will enter user name and password and follow the authentication process.
  3. The external Login page includes allowing some permissions, 2-factor authentication, etc which the user needs to perform to proceed.
  4. Once above steps are successful, it will be redirected to Callback URL (not yet created). This step can be skipped and immediately redirected to next step.
  5. After user is successfully authenticated, screen in the mobile app will be redirected to home page created in Ionic.

Questions:

  1. Is it possible to display the login page inside Ionic content?
  2. How to handle call back in Ionic so it will display home page after successful authentication?
  3. What are the other options?

Thanks in advance

You can use an InAppBrowser and then listen for a URL to the callback URL, something like this:

login(){
 
  return new Promise((resolve, reject) => {
 
    let browser = this.iab.create(this.url, '_blank');
 
    let listener = browser.on('loadstart').subscribe((event: any) => {
 
      //Check the redirect uri
      if(event.url.indexOf(this.redirectURI) > -1 ){
        listener.unsubscribe();
        browser.close();
        let token = event.url.split('=')[1].split('&')[0];
        this.accessToken = token;
        resolve(event.url);
      } else {
        reject("Could not authenticate");
      }
 
    });
 
  });
 
}

Your exact implementation will differ slightly, of course.

Thanks for the quick response.

It generates the following error message:

Error: Uncaught (in promise): TypeError: browser.on(…).subscribe is not a function
TypeError: browser.on(…).subscribe is not a function

Have I perhaps missed any?

I run the above code on my computer and it opened a new window. Will this also open a new window or browser on mobile device?

Thanks

The code I posted isn’t going to work for your particular use case, it’s just supposed to give you an idea of the approach, which is basically: launch an InAppBrowser, listen for URL changes.

This code is designed specifically for using the InAppBrowser plugin on a real device, not for running through a normal desktop browser. It’s also been a while since I’ve used it so the InAppBrowser API may have changed since then.

I see. Thanks for the info. Will test this on a real device.

Just to confirm guess it’s not possible to render a web page inside Ionic content and listen for changes? Is this correct?

Thanks!