Skip to main content

Session and Token Lifecycle Management

Effective session and token lifecycle management is fundamental to securely and reliably integrating the Entrupy iOS SDK. All SDK operations, not just the authentication capture flow, require a valid authorization token. This document details how to obtain, use, and manage these tokens.

The Entrupy iOS SDK relies on short-lived session tokens. These tokens authorize the SDK to perform operations on behalf of a user for a limited time. Your application is responsible for obtaining these tokens from your backend, which in turn procures them from the Entrupy API, and for managing their validity.

1. Obtaining an Authorization Token

The process of obtaining an authorization token involves a client-side request generation step followed by a backend signing process.

Client-Side Request Generation

Your application must first generate an SDK authorization request string. This string is then sent to your backend for signing.

// Swift
// Generates a string to be passed to your app's backend for signing
let sdkAuthorizationRequest = EntrupyApp.sharedInstance().generateSDKAuthorizationRequest()

// Send 'sdkAuthorizationRequest' to your backend.

Backend Signing Process (Conceptual Overview)

Once your backend receives the sdkAuthorizationRequest string from your app, it must perform the following steps:

  1. Validate the App User: Ensure the request is from an authenticated and authorized user of your application.
  2. Call the Entrupy API: Your backend makes a request to the Entrupy API endpoint /v2/integrations/authorize-user (typically POST https://api.entrupy.com/v2/integrations/authorize-user). This request includes the sdk_authorization_request along with user details such as unique_user_id, email, first_name (optional), and last_name (optional).
    • The unique_user_id is an important identifier (8-40 characters: A-Za-z0-9@.+_-) that your system uses to represent the user. It's important that this ID is stable and permanently associated with the end-user, as it's used for tracking authentications and other Entrupy services.
    • The user's email, first_name, and last_name are set permanently upon the first call for a given unique_user_id. Subsequent calls with differing information for these fields might result in a 409 Conflict (though a valid signed request will still be returned).
  3. Receive Signed Request: The Entrupy API, if successful, returns a signed_authorization_request and a username (e.g., OrganizationName-example-user-id) to your backend.
  4. Return to App: Your backend then securely transmits the signed_authorization_request back to your mobile application.
Backend Implementation Details

For a comprehensive guide on implementing the backend logic for signing SDK authorization requests, please refer to the Essential Backend Integration Tasks document.

Receiving the Signed Authorization Request in-App

Your application will receive the signed_authorization_request string from your backend as part of its standard network communication (e.g., in the response of an HTTPS request).

2. Logging into the SDK

With the signed_authorization_request obtained from your backend, your application can log the user into the Entrupy SDK.

// Swift
// Assuming 'data' is the Data object received from your backend containing the signed request
if let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
if let signedRequest = jsonObject["signed_authorization_request"] as? String {

// Implement the EntrupyLoginDelegate protocol (see below)
EntrupyApp.sharedInstance().loginDelegate = self
EntrupyApp.sharedInstance().loginUser(withSignedRequest: signedRequest)
}
}

EntrupyLoginDelegate Implementation

To handle the outcome of the login attempt, you must implement the EntrupyLoginDelegate protocol.

// Swift
extension YourViewController: EntrupyLoginDelegate {

// Invoked if the login was successful
// Save the received authorization token expiry timestamp.
// Use this timestamp to proactively re-authorize the user when the token is about to expire.
func didLoginUserSuccessfully(_ expirationTime: TimeInterval) {
UserDefaults.standard.set(expirationTime, forKey: "entrupyTokenExpiry")
print("Entrupy SDK login successful. Token expires at: \(expirationTime)")
// Proceed with SDK operations
}

// Invoked if the login was unsuccessful
func didLoginUserFailWithError(_ errorCode: EntrupyErrorCode, description: String, localizedDescription: String) {
print("Entrupy SDK login failed. Error: \(localizedDescription) (Code: \(errorCode.rawValue))")
// Handle the error, e.g., show an alert to the user.
// Refer to error-code-reference.md for details on error codes.
switch (errorCode) {
// Handle specific errors as needed
default:
showAlert(title: "Login Error", message: localizedDescription)
}
}
}

3. Token Validity and Management

Managing the lifecycle of the authorization token is important for uninterrupted SDK functionality.

Checking Token Validity

Before making calls to SDK functions that require authorization, check if the current token is still valid.

// Swift
if (EntrupyApp.sharedInstance().isAuthorizationValid()) {
// Token is valid, proceed with SDK call
// e.g., EntrupyApp.sharedInstance().startCapture(...)
} else {
// Token is not valid or has expired.
// Initiate the re-authorization process (Steps 1 & 2).
print("Entrupy token is invalid. Re-authorization required.")
}

It is good practice to perform this check before initiating any SDK workflow that depends on user authorization.

Token Expiration and Re-authorization

Authorization tokens are short-lived and will expire. Your application must proactively manage re-authorization.

  1. Store Expiration Time: When didLoginUserSuccessfully(_ expirationTime: TimeInterval) is called, save the expirationTime (a Unix timestamp).
  2. Proactive Check: Periodically, or before critical SDK operations, compare the current time against the stored expirationTime.
  3. Re-authorize: If the token is close to expiring or has expired, repeat the process of "Obtaining an Authorization Token" (Section 1) and "Logging into the SDK" (Section 2) to get a new token.

A seamless re-authorization process, ideally happening in the background before the user attempts an action requiring it, will provide the best user experience.

SDK Initialization

Note that the overall Entrupy SDK must be initialized (e.g., with your API key and environment settings, often in your AppDelegate or SceneDelegate) before user-specific login and token management can occur. This document focuses on the user session token lifecycle.

4. SDK Cleanup

When a user logs out of your application or switches accounts, you should clean up the Entrupy SDK session state.

// Swift
// Call this on user logout or before switching user accounts
EntrupyApp.sharedInstance().cleanup()

This ensures that any cached user-specific data or session information within the SDK is cleared.

5. Important Considerations

  • Security: The process of signing the sdkAuthorizationRequest must occur on your secure backend. Never embed sensitive credentials or attempt to sign requests directly within your mobile application.
  • Rate Limiting: Be mindful of API rate limits, especially for the /v2/integrations/authorize-user endpoint used by your backend and the /login route used by the SDK. The /login route (utilized by loginUser(withSignedRequest:)) typically has stricter limits (e.g., 5 successful logins per minute, 100 per day per user, though test users may have higher limits). Refer to Section 14 of sdk-v1-legacy.md or the Error Code Reference for ErrorCodeTooManyRequests.

By carefully managing the session and token lifecycle, you can ensure a smooth and secure experience for your users when interacting with Entrupy SDK features.