Skip to content

AppLogin⚓︎

Generally, there are two categories of app that are built with the nextAuth Mobile SDK:

  • authenticator apps: apps used to authenticate the user on websites, other apps, ...; and
  • apps with personalised or paying functionality that require logging in.

This scenario describes the latter, i.e. apps that require an AppLogin. An AppLogin is a special session, which is tied to the activity of the mobile app. It is used to let the user log in to the app itself, which can then use that session to access a backend directly.

Warning

The AppLogin functionality from the Mobile SDK assumes that the app has (at most) a single account. If you require more than one account in your app, get in touch with your nextAuth technical support contact.

Warning

The AppLogin functionality requires continuous authentication, i.e., make sure that the "pingTime" of the nextAuth server you are connecting to, is sufficiently high. We recommend setting it to a value of at least 300 (five minutes) for critical apps and even to 600 (ten minutes) or higher for other apps.

You can use the following server API calls to get and update your server's parameters.

Configuring SDK⚓︎

We recommend the following settings for the Mobile SDK configuration:

...
"appLoginInactivityTimeout":"5m",
"singleAccount":true,
...
...
<key>NAAppLoginInactivityTimeout</key>
<string>5m</string>
<key>NAAppLoginRequired</key>
<true/>
<key>NASingleAccount</key>
<true/>
...

This assumes a five-minute inactivity timeout on your AppLogin. Obviously, you can also set appLoginInactivityTimeout to higher values (see the Configuration Reference for more details).

Info

The AppLogin's inactivity timeout is measured through calls made to the nextAuth mobile SDK that imply user interaction. This includes for instance getting a list of sessions or accounts, since the app is most likely to only make these calls if your app is actively used. Calls related push notifications do not update the AppLogin's inactivity timeout as these are processed automatically without implying user interaction.

High-Level App Flow when Using AppLogin Functionality

High Level App Flow⚓︎

At every entry point of the app, it should check whether or not an account exists. If not, the user should be redirected to your onboarding flow. If so, one should check whether the AppLogin is active. Otherwise, the user should be redirected to your login flow.

Remember that the nextAuth mobile SDK works asynchronously, and that you thus also need to listen for callbacks globally.

Implement the following in the onResume() method of every Activity that should only be accessible when the app is logged in.

if (NextAuth.getNextAuth().getAccountManager().getAccounts().size() > 0){
    if (!NextAuth.getNextAuth().getAppLogin().isLoggedIn()){
        // TODO: Show your AppLogin flow
    }
} else {
    // TODO: Present your onboarding flow
}

In contrast to Android, iOS applications only have a single entry point. We therefore recommend introducing a root view controller which will handle checking whether an account exists and if an AppLogin is active.

if let count = NextAuth.default.accounts?.count, count > 0 {
    guard let isLoggedIn = NextAuth.AppLogin.session?.isLoggedIn, !isLoggedIn else {
        return
    }

    // TODO: Show your AppLogin flow
} else {
    // TODO: Present your onboarding flow
}

Your app should also listen for callbacks/notifications telling it that a session has logged in, stopped or an account was removed:

  • for a logged-in session, you should check if this is an AppLogin, if so you can access the webNonce and username;
  • for a stopped session, you should check if the AppLogin is still active and redirect the user to your login flow otherwise;
  • for a removed account, the user should be redirected to the onboarding flow.

Add the following to the onCallback(Callback callback) method of MyApplication:

if (callback instanceof SessionLogin){
    if(NextAuth.getNextAuth().getAppLogin().isLoggedIn()){
        // Your app is now logged in and you can now request the webNonce and username
        String webNonce = NextAuth.getNextAuth().getAppLogin().getWebNonce();
        String username = NextAuth.getNextAuth().getAppLogin().getUserName();
    }
}
if (callback instanceof SessionStop) {
    if (!NextAuth.getNextAuth().getAppLogin().isLoggedIn()) {
        // TODO: Show your AppLogin flow
    }
}
if (callback instanceof AccountDeleted){
    if (NextAuth.getNextAuth().getAccountManager().getAccounts().size() == 0){
        // TODO: Present your onboarding flow
    }
}

As you might recall from the Setup section, our iOS Mobile SDK posts local notifications when a session's state changes. You should therefore register handlers for NextAuth.NotificationNames.accountDelete (available from v1.8.0) and NextAuth.NotificationNames.sessionUpdate as follows.

// MARK: - Observers

@objc func handleAccountDeleteNotification(_ notification: NSNotification) {
    guard let count = NextAuth.default.accounts?.count, count > 0 else {
        return
    }

    // TODO: Present your onboarding flow
}

@objc func handleSessionUpdateNotification(_ notification: NSNotification) {
    guard let session = notification.object as? Session, session.isAppLogin else {
        return
    }

    if session.isLoggedIn {
        // Your app is now logged in and you can now request the webNonce and username
        let webNonce = session.webNonce
        let username = session.username
    } else {
        if session.isLoggedOut {
            // TODO: Show your AppLogin flow
        }
    }
}

// MARK: - UIViewController

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(handleAccountUpdateNotification(_:)), name: NextAuth.NotificationNames.accountUpdate, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(handleAccountDeleteNotification(_:)), name: NextAuth.NotificationNames.accountDelete, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(handleSessionUpdateNotification(_:)), name: NextAuth.NotificationNames.sessionUpdate, object: nil)
}

Tip

After your onboarding flow has finished, i.e. when you receive a SessionLogin callback, you should trigger an AppLogin to ensure a consistent user experience. If done immediately, the user will not be asked again for inputting their second factor and hence the AppLogin will be transparent to the user.

Logging In⚓︎

An AppLogin can be started directly in the Mobile SDK. There is no need to provide additional information, such as a QR code or a deep link, as it is the app itself that initiates the session, not a browser or other mobile app.

NextAuth.getAppLogin().start();
NextAuth.AppLogin.start()

Handling Callbacks⚓︎

The user will not be asked to confirm, but will go directly to the input of the second factor. The expected sequence of callbacks/notifications to be handled is as follows:

  1. SecondFactor with VERIFY as its context -- asking the user to enter their second factor for verification. See here for more information.
  2. SecondFactor with SUCCESS as its result -- acknowledging that the second factor has been verified.
  3. SessionLogin -- acknowledging that the user is now logged in.
  1. didStartSecondFactorWith with VERIFY as its context -- asking the user to enter their second factor for verification. See here for more information.
  2. didUpdateSecondFactorWith with SUCCESS as its result -- acknowledging that the second factor has been verified.
  3. sessionUpdate -- acknowledging that the user is now logged in.

While Being Logged In⚓︎

An identifier for securely retrieving backend data (webNonce) and the username can be retrieved directly from the AppLogin session (at any time while being logged in). This webNonce allows the backend to verify with the nextAuth server who is logged in for that AppLogin.

String webNonce = NextAuth.getNextAuth().getAppLogin().getWebNonce();
String username = NextAuth.getNextAuth().getAppLogin().getUserName();
NextAuth.AppLogin.session?.webNonce
NextAuth.AppLogin.session?.account?.username

Info

If one or more backends to retrieve data from, cannot communicate with the nextAuth server directly, it is a good idea to implement a (OAuth 2.0) token service endpoint, which does communicate with the nextAuth server and can hence check that there is someone logged in for the given webNonce. In this scenario, the app then first requests a (OAuth 2.0) token based on the webNonce at this token service and then uses the received (OAuth 2.0) token to retrieve data from the backend(s).

Logging Out⚓︎

A logout of an AppLogin session can be triggered in a number of ways:

  • explicitly from within the app, by stopping the AppLogin session;

    NextAuth.getAppLogin().stop();
    
    NextAuth.AppLogin.stop()
    
  • implicitly from within the app, if a timeoutInactivityAppLogin is configured: if in this time there was no user interaction;

  • explicitly from the server, when the app receives a message from the server telling it to stop the session;

On logging out an AppLogin session, the result of the last successful second factor verification is removed from memory.

Attention

After logging out an AppLogin session, the user will always be required to provide their second factor for the next authentication.