Client code integration
This guide explains how to integrate the proof-of-concept authentication flow into your client application.
The guide is organized as follows:
- Set up proof-of-concept authentication: Copy the required authentication helpers and dependencies into your project.
- Register a callback scheme: Configure your app to receive the authentication result after sign-in.
- Implement authentication in your app: Start sign-in, handle the callback, establish a user session, and enable Niantic Spatial access.
- Use tokens in your app: Manage access tokens and handle expiration.
Niantic Spatial Access tokens are JSON Web Tokens (JWTs) used to authorize requests to Niantic Spatial services.
When testing with the sample applications, the client-side code handles fetching and refreshing these tokens automatically. In a production application, your backend is responsible for requesting tokens from Niantic Spatial and supplying them to the NSDK through your application code.
Niantic Spatial Access tokens expire after a set period. On login, the client should verify the token’s validity using the expiration timestamp provided by the backend. If the token is missing or expired, request a new one from your backend. Never refresh tokens directly in the client.
This guide focuses on client-side token usage. Backend token issuance is explained in Generate access tokens. For testing or proof of concept, see Authorization.
Set up proof of concept authentication
You can try out NSDK functionality in one of two ways:
- Modify the sample application to include your own functionality.
- Copy the authentication code into a new application, register the correct callback scheme, and then build your functionality on top of it.
In the proof-of-concept flow, your app authenticates directly with the Niantic Identity Service and receives tokens without requiring a backend.
Implementation details vary by platform. The following files contain the core components of the client authentication flow. Each platform also requires additional supporting files.
| File Name | Description |
|---|---|
LoginManager | Opens the login page and handles the response. |
UserSessionManager | Maintains the user session locally on the device while the app is running. |
RequestRuntimeRefreshToken | Exchanges a user session refresh token for a runtime refresh token used by the NSDK. |
You can test token handling and try NSDK features as follows:
Use Unity 6.3 LTS or a compatible version when working with the NSDK Unity samples.
-
Clone the Unity samples repository.
git clone https://github.com/nianticspatial/nsdk-samples-csharp -
Copy the authentication helpers and required supporting files into your Unity project.
-
In the cloned repository, locate the authentication files:
Assets/Samples/AuthAssets/Samples/Auth/Scripts
-
In your Unity project, create the following folder:
Assets/Auth/Scripts
-
Copy these scripts into that folder:
LoginManager.csUserSessionManager.csAuthAccessManager.csRequestAuthAccess.csRequestUserSessionAccess.csAuthEndpoints.csNianticSpatialAccessManager.cs
-
-
After you copy the authentication scripts, update the Unity sample redirect type if needed. For iOS builds, Unity uses
nsdk-unity-samplesby default. To avoid conflicts, change the redirect type inLoginManager.cs. For example, replaceredirectType=nsdk-unity-sampleswithredirectType=nsdk-external.infoNSDK limits redirect schemes for security reasons. Unity uses
nsdk-unity-samplesby default. If you need a different supported scheme, usensdk-external. NSDK does not support custom schemes. If a device reports a conflict for a redirect scheme, remove the app from the device and reinstall it. -
Add the NSDK package required by the authentication scripts by opening your project’s
Packages/manifest.jsonfile and adding the following dependency inside the"dependencies"section:"com.nianticspatial.nsdk": "https://github.com/nianticspatial/nsdk-library-upm.git" -
Follow the steps in Register a callback scheme and Implement authentication in your app.
Register a callback scheme
After sign-in, the authentication flow redirects to a URL using your app’s callback scheme. Your app must be configured to handle this redirect so it can receive the authentication result.
The redirect URL uses the format:
<your-app-scheme>://signin/redirect?refreshToken=...
The callback scheme you register must match the scheme used by the authentication redirect URL. This is the URL that returns to your app after sign-in.
Use the following steps to register the callback scheme.
In Unity, configure the URL scheme in Unity to receive the login redirect for either iOS or Android as follows:
iOS:
- Navigate to Edit → Project Settings → Player from Unity's main menu.
- Select the iOS tab.
- Expand Other Settings.
- Find and expand Supported URL schemes.
- Increment Size to add a new entry. For example, if the number is
0, enter1. Unity will create a new row where you can enter a URL scheme that begins with Element. - Enter a URL scheme in the text box that appears next to Element.
Unity will store the URL scheme in ProjectSettings/ProjectSettings.asset. When you build for iOS, Unity generates an Xcode project and converts your Unity settings into iOS config files called
Info.plist. Once you update the URL scheme, you must rebuild the iOS project so that Xcode sees the update.
Android:
-
Navigate to Assets folder in Unity's left navigation pane.
-
Create or open a new activity file using the folder structure
Assets/Plugins/Android/AndroidManifest.xml. -
Add the following intent filter to your activity. Use a callback scheme that matches your authentication configuration. The value must match the scheme used in your authentication code.
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="nsdk-unity-samples" android:host="signin" />
</intent-filter>The following example shows the minimum Android manifest content for this intent filter:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
<application>
<activity android:name="com.unity3d.player.UnityPlayerActivity" android:theme="@style/UnityThemeSelector" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="nsdk-unity-samples" android:host="signin" />
</intent-filter>
</activity>
</application>
</manifest>
Implement authentication in your app
This section shows how to add the sample login flow to your app code. The steps include:
- Start sign-in
- Handle the authentication callback
- Establish the user session
- Configure Niantic Spatial access
Start sign-in
This section shows how to initiate the login flow from your app’s UI or script by calling the sample login manager.
Before starting sign-in, initialize the authentication endpoints used by the sample login flow. The login manager reads endpoint URLs from this configuration at runtime, so it must be set before calling LoginManager.LoginRequested().
- In the Unity Project window, select Create → Scriptable Objects → AuthEndpoints to create the asset.
- Add a script to your scene to initialize it. The following script example initializes settings reference for the
AuthEndpointsobject:using UnityEngine;
public class AuthEndpointsInitializer : MonoBehaviour
{
[SerializeField] private AuthEndpoints authEndpoints;
private void Awake()
{
authEndpoints.SetAsSettings();
}
} - Add this script to a
GameObjectin your scene and assign theAuthEndpointsasset in the Inspector.
To start the sign-in flow in Unity, call LoginManager.LoginRequested() from a script that runs in response to user input, such as a UI button.
The following example starts sign-in from a UI button:
using UnityEngine;
public class LoginController : MonoBehaviour
{
public void OnLoginTapped()
{
LoginManager.LoginRequested();
}
}
Add this script to a GameObject in your scene. Then connect OnLoginTapped() to a UI Button in the Inspector.
Handle the authentication callback
After sign-in completes, your app receives the authentication result through a callback URL. This URL contains the tokens required to establish a user session.
Unity delivers the authentication result to your app through a deep link. When the browser finishes sign-in, it redirects to your app using the callback scheme you registered.
The sample login flow handles this automatically. Calling LoginManager.LoginRequested() sets up the deep link listener and processes the returned URL when your app resumes.
No additional callback-handling code is required unless you are customizing the authentication flow.
Establish the user session
This section shows how to store the returned tokens in UserSessionManager so your app can maintain a signed-in session.
When sign-in completes, LoginManager extracts the returned access token and refresh token from the redirect URL and stores them in UserSessionManager.
The following code in LoginManager.cs completes the sign-in flow:
private static void OnDeepLinkActivated(string url)
{
Application.deepLinkActivated -= OnDeepLinkActivated;
IsLoginInProgress = false;
var userSessionAccessToken = GetParamValue("accessToken", url);
var userSessionRefreshToken = GetParamValue("refreshToken", url);
UserSessionManager.SetUserSession(userSessionRefreshToken, userSessionAccessToken);
LoginComplete?.Invoke();
}
After sign-in completes, your app should return to the scene and continue running without errors. At this point, the user session is established automatically.
Configure Niantic Spatial access
This section shows how to enable Niantic Spatial access after sign-in.
To enable NSDK features, set up the access flow before starting sign-in.
The sample login flow stores user session tokens after sign-in. You must also add a listener that starts the Niantic Spatial access flow when login completes.
Add the following script to a GameObject in your scene before starting sign-in:
using UnityEngine;
public class AuthAccessController : MonoBehaviour
{
private void OnEnable()
{
LoginManager.LoginComplete += OnLoginComplete;
}
private void OnDisable()
{
LoginManager.LoginComplete -= OnLoginComplete;
}
private void Start()
{
UserSessionManager.Start();
if (!string.IsNullOrEmpty(UserSessionManager.AccessToken))
{
AuthAccessManager.StartAuthAccess(UserSessionManager.AccessToken);
}
}
private void OnLoginComplete()
{
AuthAccessManager.StartAuthAccess(UserSessionManager.AccessToken);
}
}
After login completes, AuthAccessManager requests Niantic Spatial access and refreshes it automatically while the app is running.
Once authenticated, your app uses the access token as described in the following sections.
Going to production using your own backend
In production, your backend must issue and manage access tokens for each logged-in user. See Generate access tokens for server-side setup.
On the client side:
- Receive a short-lived access token from the backend on login.
- Provide the access token to the NSDK.
- Periodically check the token’s expiration time.
- Refresh the access token a few minutes before it expires by requesting a new token from your backend.
- When you receive a new token, set it on the NSDK.
The following sections show how to initialize, update, and clear access tokens in your app.
Use tokens in your app
This section shows you how to:
- Set access tokens in your NSDK session.
- Periodically check if a token has expired or is about to expire.
- Clear tokens on logout.
Set the access token when initializing the NSDK session as follows:
using NianticSpatial.NSDK.AR.Loader;
NsdkSettingsHelper.ActiveSettings.AccessToken = accessToken
Check if the access token has expired or will expire soon. Use AuthClient.GetAccessAuthInfo to obtain an AuthInfo object containing the expiration time in seconds since the Unix epoch. Compare it to the current time to determine if a new token is needed as follows:
using NianticSpatial.NSDK.AR.Auth;
/// <summary>
/// Returns true if access has expired or is about to expire in under a minute.
/// Uses <see cref="AuthClient.GetAccessAuthInfo"/> to read the access token's expiration.
/// </summary>
/// <returns>true if access is expired or expires in under 60 seconds; false otherwise.</returns>
public static bool IsAccessExpiredOrExpiringSoon()
{
var authInfo = AuthClient.GetAccessAuthInfo();
var currentTimeSeconds = (int)DateTimeOffset.UtcNow.ToUnixTimeSeconds();
var timeLeft = authInfo.ExpirationTime - currentTimeSeconds;
return timeLeft < ExpiringSoonThresholdSeconds;
}
Clear the access token to prevent further NSDK access until a new token is obtained as follows:
NsdkSettingsHelper.ActiveSettings.AccessToken = string.Empty