Search code examples
authenticationionic-frameworkionic2

Ionic 2 how to make InAppBrowser and other plugins work when running in a browser


I'm creating a app in Ionic 2, which consumes a web API from an existing site. To use this API I have to make authenticate in it in the following way (Similar to Facebook login):

  • I call the API login page in a InAppBrowser component, sending the proper keys and a return URL.
  • the user types the login and password in the form displayed, the API will validate it and authenticate it.
  • The API calls the return URL passing the authorization token.
  • I 'hijack' this redirect to the return URL in the InAppBrowser 'loadstart' event, and extract and store the authorization token.
  • In the following calls to the API, I send the authorization token in the header.

This is all working fine in the emulator, but it doesn't work in the browser (with ionic serve), because when I call InAppBrowser it actually calls window.open, and the events doesn't work. I can't detect the redirect action made in the opened window.

I'd like to make this work in the browser since its better to debug the application there. My first thought was to send "http://localhost:8001" as the return URL, but I couldn't find a way to catch the token parameter in the ionic application.

Does anyone know how I can catch this parameter or any other way to make this login work in the browser? It is for development and debug purposes only, so strict security is not a issue (I can comment out any unsecure code in the production version).


Edit: Hayden Braxton answer didn't solve my problem, but since it was because of something exclusively to my app, and it could really help someone who wants to make plugins work, I'll keep it as the selected answer.

Besides that, I'll share the solution I found to my problem in case it could help anyone. It was simple, actually:

  • I pass "http://localhost:8001" as the API return_uri parameter
  • the API will, after checking the login and password, redirect to http://localhost:8001?token=MY_AUTH_TOKEN.
  • This will reload the application and call login page again.
  • In the login page I call this.platform.getQueryParam("token"); to get the token.

Solution

  • Add

    "browser": "ionic-app-scripts serve --iscordovaserve --sourceMap source-map  --wwwDir platforms/browser/www/ --buildDir platforms/browser/www/build",
    

    to the script section of your package.json. Then instead of doing ionic serve, instead run

    npm run browser
    

    We use ionic2 to develop our apps where I work, and this is what we figured out after some research.

    Before using this, you need to have the browser platform added. You can accomplish this with the following:

    ionic add platform browser
    

    If the browser platform is already added, delete the browser directory from your platforms directory and then run the add platform command, just to be on the safe side.