Setup⚓︎
In this section, we will explain how to access the Mobile SDK, import it into your project and initialise it. Furthermore, since the Mobile SDK works asynchronously, you will need to set up listening for callbacks from it. After these steps, you can proceed to enrol your first account.
Minimal Requirements⚓︎
The Mobile SDKs require Android 6.0 (or above) and iOS 15.0 (or above).
Access to the Mobile SDKs & Docs⚓︎
The Android and iOS Mobile SDKs are available from our GitLab server at https://git.nextauth.com/. If you have trouble accessing the site, please contact your nextAuth support representative.
Each Mobile SDK comes with a full, machine-readable reference manual for the respective public API. For Android, this is a JavaDoc archive distributed as a Maven package together with the SDK. For iOS, the reference manual is included in the Git repository under the docs directory.
The SDKs are distributed as releases. Within each release, you can find the accompanying release notes. It is possible to subscribe to receive release notifications from within our GitLab interface if you wish to be notified when new releases are available.
Importing the Mobile SDK⚓︎
Android⚓︎
-
First, sign in to the nextAuth GitLab interface, and then generate a personal access token with the read_api scope.
-
Next, create a file called
~/.gradle/gradle.propertieswith the following content.
gitLabPrivateToken={PERSONAL_ACCESS_TOKEN}
- Then, add the following commands to your project’s
build.gradlescript.
allprojects {
repositories {
...
maven {
url "https://git.nextauth.com/api/v4/projects/3/packages/maven"
name "GitLab"
credentials(HttpHeaderCredentials) {
name = 'Private-Token'
value = gitLabPrivateToken
}
authentication {
header(HttpHeaderAuthentication)
}
}
...
}
}
- Continue by declaring the nextAuth Android SDK dependency in your module’s
build.gradlescript. (The placeholder{VERSION}should be replaced with the correct version of the package, for example3.0.0.)
dependencies {
...
implementation 'com.nextauth.android:nextauth:{VERSION}'
...
}
- Finally, add the following features and permissions to the
AndroidManifest.xmlfile for your app.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
// needed for scanning QR codes
<uses-feature
android:name="android.hardware.camera"
android:required="false" />
<uses-feature
android:name="android.hardware.camera.front"
android:required="false" />
<uses-permission android:name="android.permission.CAMERA" />
// needed for biometrics
<uses-feature
android:name="android.hardware.fingerprint"
android:required="false" />
<uses-permission android:name="android.permission.USE_BIOMETRIC" />
// needed for notifications
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
iOS⚓︎
Our iOS Mobile SDK is distributed as a CocoaPod.
-
First, sign in to the nextAuth GitLab interface, and then generate a personal access token with the read_api scope.
-
Next, create a file called
.netrcin your home directory with the following contents. (The placeholder text strings {USERNAME} and {PERSONAL_ACCESS_TOKEN} must be replaced with your appropriate details.)
machine git.nextauth.com login {USERNAME} password {PERSONAL_ACCESS_TOKEN}
-
We also strongly recommend changing the permissions of this file so that it is accessible only by the owner (e.g.
0600or0400file permissions on Unix-like development systems). -
Finally, you can import the NAKit module by adding the following directives to your project’s
Podfile:
def pod_nakit
def http(version)
"https://git.nextauth.com/api/v4/projects/4/packages/generic" \
"/NAKit/#{version}/NAKit_v#{version}.zip"
end
pod 'NAKit', :http => http('{VERSION}'), :type => :zip
end
Alternatively, you can also include the Mobile SDK as a Swift Package. To do this, place the following code in a file called Package.swift in the NAKit directory and then add the Package to your project.
// swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "NAKit",
platforms: [.iOS(.v15)],
products: [
.library(name: "NAKit", targets: ["NAKit"])
],
targets: [
.binaryTarget(
name: "NAKit",
url: "https://git.nextauth.com/api/v4/projects/4/packages/generic/NAKit/{VERSION}/NAKit_v{VERSION}.zip",
checksum: ""
)
]
)
Initialising the Mobile SDK⚓︎
Android⚓︎
Before initialising the SDK, ensure that you have a file called nextauth.json in the assets folder of the app. (The portion after the colon : must be filled in with the signed configuration string that should have been provided to you by your nextAuth support representative.)
{
"config": ""
}
See here for other optional configuration parameters that can be added to the configuration file.
The SDK operates as a singleton class and should therefore be initialised at the application level. Create your custom MyApplication which extends android.app.Application and then initialise the SDK by calling the NextAuth.init(Context) method, passing the application context as the input argument.
import com.nextauth.android.NextAuth;
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// Initialise nextAuth Mobile SDK
NextAuth.init(getApplicationContext());
}
}
Info
As an alternative to working with the constants file, it is also possible to define a Constants object programmatically and to pass this along as an input to the init method:
Constants constants = new Constants();
constants.config = "";
...
NextAuth.init(getApplicationContext(), constants);
iOS⚓︎
Once the Pod or Package has been installed, the Mobile SDK should be configured before any other interaction takes place.
Warning
Don’t forget to customise the value of the config parameter. This is mandatory for the app to operate correctly. In addition, there are other parameters that allow you to customise the app’s behaviour.
Warning
When you want to run your app on-device, you must first create an App Group in Apple’s Developer portal. This will typically have the form group.com.nextauth.Authenticator. Once it has been created, please also ensure to grant the app’s Bundle ID the capability to access that group, to update your provisioning profiles, and to set the appGroup parameter.
The final task to take care of on the iOS side, is to configure the Mobile SDK. The following Swift code demonstrates the required steps:
let constants = NextAuth.Constants(
config: "",
appGroup: "",
)
guard NextAuth.default.canBeConfigured else {
return
}
NextAuth.default.configure(withConstants: constants)
Setting up Callback Listeners⚓︎
There are two types of callbacks: callbacks to handle errors (e.g. error, panic) and those for updating the UI (e.g. flow updates, session updates, account updates, deletion of account).
As for callbacks that handle errors, we distinguish between non-fatal errors and panics. A non-fatal error should generally be shown to the user. A panic represents an unrecoverable error. In the case of a panic, the only recourse is to log the event both locally and remotely before the app crashes.
The general idea is to listen for those events that require user interaction at the top level (the application on Android, or the top level view controller on iOS) and then to start specific activities (Android) or views (iOS) for capturing the user’s input. Then, your app can listen to UI updates from within those specific activities or views.
Android⚓︎
To listen for callbacks, your class needs to implement the NextAuthObserver interface by overriding the onCallback(Callback callback) method. Objects of the class must also register themselves as an observer by calling NextAuth.addObserver(this).
Callbacks to Handle Errors⚓︎
You can implement the top level user interaction by extending myApplication as follows:
import com.nextauth.android.callback.Callback;
import com.nextauth.android.callback.Error;
import com.nextauth.android.callback.Panic;
import com.nextauth.android.NextAuth;
public class MyApplication extends Application implements NextAuthObserver {
@Override
public void onCreate() {
super.onCreate();
// Initialise nextAuth Mobile SDK
NextAuth nextAuth = NextAuth.init(getApplicationContext());
// Register observer
nextAuth.addObserver(this);
}
// Handle global callbacks
@Override
public void onCallback(Callback callback) {
if (callback instanceof Error) {
// TODO: Handle errors not associated with a flow
}
if (callback instanceof Panic) {
// TODO: log panic
// crash the app, as a panic indicates an unrecoverable state in the nextAuth Mobile SDK
throw new RuntimeException(((Panic) callback).nextAuthException);
}
}
}
Callbacks to Update the UI⚓︎
When starting a flow, you will need to listen for flow updates. On Android, you can always obtain the current flow using the flow manager, which will either return a Flow if one is active or null if there is no active flow:
NextAuth.getNextAuth().getFlowManager().getFlow();
Tip
Android apps typically have multiple entry points. We recommend calling the NextAuth.getFlow() method in every entry point’s onResume() method to check for an ongoing flow that needs user interaction.
Tip
You can also add a nextAuthObserver to the QR code scanner/camera activity and then finish this activity when receiving a FlowUpdate callback.
iOS⚓︎
On iOS, we rely on two different update mechanisms to inform you about the different types of state changes. First, you should implement the methods defined by the NextAuthDelegate protocol, which is part of our Mobile SDK. We suggest conforming to this protocol in a high-level class which has the ability to add and remove view controllers to and from the view hierarchy. Second, the Mobile SDK also issues local notifications you can subscribe to in order to receive account and session updates and to trigger relevant actions (e.g. to update a view which is showing active sessions).
After implementing the protocol, don’t forget to assign an instance of the conforming class to the delegate property of the Mobile SDK’s singleton.
// MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
NextAuth.default.delegate = self
}
Callbacks to Handle Errors⚓︎
Add the following to the class where you are implementing the NextAuthDelegate protocol in order to handle any asynchronous errors returned by the Mobile SDK.
// MARK: - NextAuthDelegate
func nextAuth(_ nextAuth: NextAuth, didReturn error: Session.Error) {
// TODO: Present alert to user
}
func nextAuth(_ nextAuth: NextAuth, didThrow panic: String) {
// TODO: Optionally log the passed panic reason
fatalError()
}
Callbacks to Update the UI⚓︎
Since you might want to trigger multiple actions based on session or account updates, we opted to have the Mobile SDK post local notifications to the NotificationCenter. The names of all notifications have been made available through the NotificationNames struct. While in some cases you simply want to know that either a session or account changed, note that we also attach the Session or Account instance that triggered the notification to the posted notification. The code snippet below will get you started on subscribing to these notifications.
// MARK: - Observers
@objc func handleAccountUpdateNotification(_ notification: NSNotification) {
guard let account = notification.object as? Account else {
return
}
// TODO: Implement required logic to process account update
}
@objc func handleAccountDeleteNotification(_ notification: NSNotification) {
guard let account = notification.object as? Account else {
return
}
// TODO: Implement required logic to process account delete
}
@objc func handleSessionUpdateNotification(_ notification: NSNotification) {
guard let session = notification.object as? Session else {
return
}
// TODO: Implement required logic to process session update
}
// 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)
}