Configure an iOS app for OATH MFA
PingOne Advanced Identity Cloud PingAM iOS
This page guides you through configuring your iOS application to support OATH-based Multi-Factor Authentication (MFA) using the OATH module.
It covers dependency setup, OATH client initialization, credential management, passcode generation, and custom storage options.
Step 1. Adding core dependencies
You can use Swift Package Manager (SPM) or CocoaPods to add dependencies to your iOS project.
Swift Package Manager
-
With your project open in Xcode, select File > Add Package Dependencies.
-
In the search bar, enter the Orchestration SDK for iOS repository URL:
https://github.com/ForgeRock/ping-ios-sdk. -
Select the
ping-ios-sdkpackage, and then click Add Package. -
In the Choose Package Products dialog, ensure that the
PingOathlibrary is added to your target project. -
Click Add Package.
-
In your project, import the relevant dependencies:
import PingOath
CocoaPods
-
If you do not already have CocoaPods, install the latest version.
-
If you do not already have a Podfile, in a terminal window, run the following command to create a new Podfile:
pod init
-
Add the relevant dependencies to your Podfile:
pod 'PingOath'
-
Run the following command to install pods:
pod install
Step 2. Initializing the OATH Client
To use the OATH module you must initialize the OATH client in your application by calling the createClient() method:
// Create an OATH client
let client = try await OathClient.createClient { config in
config.logger = LogManager.logger
config.enableCredentialCache = false
}
The properties you can use to customize OATH client configuration are as follows:
- enableCredentialCache
-
Whether to enable in-memory caching of credentials.
By default, this is set to
falsefor security reasons, as an attacker could potentially access cached credentials from memory dumps. - timeout
-
The timeout for network operations, in seconds.
Default value is
15. - storage
-
The storage implementation to use for OATH credentials.
If
nil, the defaultOathKeychainStorageis used.Learn more in Customizing credential storage.
- policyEvaluator
-
The policy evaluator to use for credential policy validation.
If
nil, the defaultMfaPolicyEvaluatoris used. - encryptionEnabled
-
Whether data encryption is enabled for storing credentials.
Default is
true. - logger
-
The logger instance used for logging messages.
Defaults to a global logger instance.
Learn more in Logging.
Step 3. Managing OATH credentials
The OATH module relies on a set of credentials, that you can create, retrieve, update, and delete.
The credentials contain details such as the service and user they relate to, and details about how to generate the HOTP or TOTP key.
Creating OATH credentials
The OATH module lets the user register their device for OATH-based multi-factor authentication (MFA).
The information required to register a device is contained in a specially-encoded URI, which your client application decodes to create the credentials.
This URI is often delivered by QR codes that the client can scan, or directly in the callback output by the OATH Registration node.
Use the addCredentialFromUri() method to create OATH credentials and register an MFA device:
let uri = "otpauth://hotp/Example:user@example.com?secret=JBSWY3DPEHPK3PXP&counter=0"
let credential = try await client.addCredentialFromUri(uri)
Getting OATH credentials
You can get a list of all the registered OATH credentials, or get an individual credential, by passing the credential ID as a parameter.
-
All OATH credentials
-
Specific OATH credential
do {
let credentials = try await Task.detached(priority: .userInitiated) {
try await client.getCredentials()
}.value
} catch {
throw AppError.oathError("Failed to load credentials: \(error.localizedDescription)")
}
let credential = try await Task.detached(priority: .userInitiated) {
try await client.getCredential(credentialId)
}.value
Updating OATH credentials
You can update the properties of a stored credential with new values, by using the saveCredential() method. Pass the updated credential object into the method as a parameter:
for credential in credentials {
var updated = credential
updated.displayIssuer = "Example.com Checking Account"
updated.displayAccountName = "Babs Jensen"
_ = try await client.saveCredential(updated)
}
Deleting OATH credentials
Use the deleteCredential() method to remove individual credentials from the client device. Pass the credential ID into the method as a parameter:
do {
let removed = try await Task.detached(priority: .userInitiated) {
try await client.deleteCredential(credentialId)
}.value
return removed
} catch {
throw AppError.oathError("Failed to remove credential: \(error.localizedDescription)")
}
Step 4. Generating OATH-based one-time passcodes
To perform OATH-based multi-factor authentication the user needs to enter the correct one-time passcode.
Your client app needs to generate these one-time passcodes and display them to the user.
Generating HOTP codes
Use the generateCode method to create an HOTP code using the details within the specified credential:
// Generate code (counter increments automatically)
let code1 = try await client.generateCode(hotpCredential.id) // Counter = 1
let code2 = try await client.generateCode(hotpCredential.id) // Counter = 2
Generating TOTP codes
For TOTP codes, the code object you generate contains timing and progress information that you can use to customize the user interface:
// Get code with timing and validity information
let codeInfo = try await client.generateCodeWithValidity(credential.id)
print("Code: \(codeInfo.code)")
print("Time remaining: \(codeInfo.timeRemaining) seconds")
print("Progress: \(codeInfo.progress * 100)%")
Step 5. Closing the OATH client
You can close the client, clean up any temporary files, and regain the memory used by calling the close() method:
// Close the OATH client and clean up
try await client.close()
Handling errors
The OATH module provides comprehensive error handling:
do {
let credential = try await client.addCredentialFromUri(uri)
} catch let error as OathError {
switch error {
case .invalidUri(let message):
print("Invalid URI: \(message)")
case .credentialNotFound(let id):
print("Credential not found: \(id)")
case .credentialLocked(let id):
print("Credential is locked: \(id)")
case .codeGenerationFailed(let message, let underlying):
print("Code generation failed: \(message)")
case .initializationFailed(let message, let underlying):
print("Client initialization failed: \(message)")
}
} catch let error as OathStorageError {
switch error {
case .storageFailure(let message, let underlying):
print("Storage error: \(message)")
}
}
Customizing credential storage
The OATH module needs to store the credentials it uses on the client device.
By default, it uses an iOS keychain services-based implementation, which you can customize.
You can also provide your own storage mechanism, by implementing the OathStorage interface.
Customizing the default keychain-based storage
The OATH module uses the OathKeychainStorage implementation for storing OATH credentials by default.
You can customize this keychain-based default as follows:
OathKeychainStorage implementation// Create a custom storage instance with specific parameters
let customStorage = OathKeychainStorage(
service: "com.myapp.oath",
accessGroup: "group.myapp",
accessibility: kSecAttrAccessibleWhenUnlockedThisDeviceOnly
)
// Create the client with the custom storage
let client = try await OathClient.createClient { config in
config.storage = customStorage
config.enableCredentialCache = false
}
The properties you can customize are as follows:
service-
The keychain service identifier.
Defaults to "com.pingidentity.oath".
accessGroup-
Optional keychain access group for shared access.
accessibility-
Keychain accessibility level.
Defaults to
kSecAttrAccessibleWhenUnlockedThisDeviceOnly.
Implementing your own storage mechanism
You can implement a custom storage solution as alternative to the default OathKeychainStorage by implementing the OathStorage interface:
class MyCustomStorage: OathStorage {
func storeOathCredential(_ credential: OathCredential) async throws {
// Store an OATH credential.
}
func retrieveOathCredential(credentialId: String) async throws -> OathCredential? {
// Retrieve an OATH credential by its ID.
}
func getAllOathCredentials() async throws -> [OathCredential] {
// Get all OATH credentials.
}
func removeOathCredential(credentialId: String) async throws -> Bool {
// Remove an OATH credential by its ID.
}
func clearOathCredentials() async throws {
// Clear all OATH credentials from the storage.
}
}