Build an Ionic App with User Authentication

dijish

This project seem to be using JHipster.I never used JHipster. Is there any other solution without using JHipster ? Is it a good practice to store the okta token in database and localstorage for future authentication?

Matt Raible

I don’t have an example with a different backend; JHipster just uses Spring Boot and Spring Security.

An access token shouldn’t be stored in a database because they’re meant to be short-lived. In this example, they’re stored in local storage, which is a common practice for single page applications.

Sean Collins

So, I did manage to sort out how to fully integrate MFA into the app with out of the box Ionic styling, but I completely blanked on the fact that it is still an Ionic app and that comes with CORS limitations. Once it was deployed to a phone, I realized that the customized handshake was all for naught and so I reverted back to the InAppBrowser solution you’d included above. Cheers and thanks again.

Khilen Maniyar

Hi Matt, Thanks for the blog. However, I’m getting Cross-Origin Error. Does it require anything to set up on UI side?

Matt Raible

Are you getting a CORS error from Okta or from your server-side app that your Ionic app talks to? If it’s Okta, make sure you have http://localhost:8100 set as a Trusted Origin (under API > Trusted Origins).

Maruti

Hi Matt,
Thanks for the awesome post, you really saved my day. I have implemented your code and it is working like a charm. Could you please give me a hint how can i auto refresh tokens. If I leave my app without doing anything after a while tokens are expiring, I dont want that to happen.
Just calling “setupAutomaticSilentRefresh” will do the trick?
Thanks!!

Matt Raible

Silent refresh is supported in angular-oauth2-oidc. However, I doubt it’ll work when running on the phone because it uses postMessage. You might have to do some research to figure out how to make it work with cordova-plugin-inappbrowser.

Khilen Maniyar

Hi Matt,
I saw, that you have already mention about window.location.origin will give file:// in the device. So, InAppBrowser is the only option for us? if I use InAppBroswer then it’s redirecting me to the Okta Login Screen. But I don’t want the Okta Screen. So what are the possible ways.

Secondly, If I think to call Login from my backend server, then it’s able to get id_token & session_token. However, it doesn’t get access_token. So could you suggest if any method to get in backend API?

Thanks,
Khilen

Matt Raible

InAppBrowser is the only way I was able to get things to work. You could try using AppAuth-JS with Ionic, but you might run into similar issues. AFAIK, you have to do a redirect to use OAuth 2.0 with Ionic.

Maruthi

Hi Matt,
In new okta/okta-auth-js 2.0, are there any changes to fix the URL redirect issue, when using Okta sign-in widget on Ionic application, without using In-App Browser?

Thanks,

Matt Raible

No, you still have to use the In-App as far as I know.

Khilen Maniyar

Hi Matt,
Any idea how we can handle tokenManager.
I added authClient.tokenManager.add(‘name’, token); but that token gets expired at certain time. And application gets closed. 2nd OAuthService doesn’t have any tokenManager functionalities so how to play with it.
Thanks.

Matt Raible

Unfortunately, I do not know how to handle this. I’d recommend posting your question to the Okta Developer Forums. It’s possible another community member has figured out a solution.

Maruthi

Hi Matt,
Can we develop IONIC app with Okta User Authorization using In-App Browser, with okta/okta-angular ? I was able to call OKTA user authentication page and user is authenticated successfully. But event.url is not having my redirect url which i configured in URL configuration.

oktaLogin(): Promise<any> {
let state: string = Math.floor(Math.random() * 1000000000).toString();
let nonce: string = Math.floor(Math.random() * 1000000000).toString();

return new Promise((resolve, reject) => {
const oauthUrl = this.buildOAuthUrl(state, nonce);
const browser = cordova.InAppBrowser.open(oauthUrl, ‘_blank’,
‘location=no,clearsessioncache=yes,clearcache=yes’);
browser.addEventListener(‘loadstart’, (event)=>{
if((event.url).indexOf(‘http://localhost:8080/’) === 0){
browser.removeEventListener(‘exit’, () => {});
browser.close();
const responseParameters = ((event.url).split(’#’)[1]).split(’&’);
const parsedResponse = {};
for (let i = 0; i < responseParameters.length; i++) {
parsedResponse[responseParameters[i].split(’=’)[0]] =
responseParameters[i].split(’=’)[1];
}
const defaultError = ‘Problem authenticating with Okta’;
if (parsedResponse[‘state’] !== state) {
reject(defaultError);
} else if (parsedResponse[‘access_token’] !== undefined &&
parsedResponse[‘access_token’] !== null) {
parsedResponse[“oktaReponse”] = responseParameters;
parsedResponse[“restAccessToken”] = parsedResponse;
resolve(parsedResponse);
} else {
reject(defaultError);
}
}else{
console.log(‘eventl url is not containing localhost8080’);
}
});
browser.addEventListener(‘exit’, function(event){
console.log(‘Flow Cancelled’);
reject(‘Flow Cancelled’);
});

});

}

Matt Raible

No, I don’t believe you can use our Okta Angular SDK with Ionic. In this example, the in-app browser replaces any Angular libraries and manually invokes URLs.

James Sunny

thank you for sharing this code.

However, have a question. How does my backend (my Server) knows that my user has been successfully logged in via Okta?

hmm I am little confused here. Do I need to integrate an Okta Backend as well?

Matt Raible

As part of the authentication process, you’ll get an access token. Then you can use this access token to talk to your protected backend. You can setup the backend as a resource server (with Spring Security, for example) that talks to Okta and validates the JWT. My Build a Basic CRUD App with Angular 7.0 and Spring Boot 2.1 tutorial shows how this works.

Jonatan Nieto

Hello Matt,

We implemented this tutorial in our app and is working find in browsers, BUT is not working in our iOS Emulator or Devices. The error is:
https://uploads.disquscdn.c…

We are using:
- Ionic 4

What happen? We are losing a lot of time, but we do no know what is the problem.

Thanks!!!

Matt Raible

This tutorial does not work with Ionic 4 AFAIK. I hope to write a new one soon, but haven’t had the bandwidth. I’d suggestion checking out capacitor-oauth2 in the meantime, or use Ionic 3.

Jonatan Nieto

Thanks Matt, We are going to try capacitor-oauth2.

Thank you!!!