redeemOtp
The redeemOtp function enables an app using the Beyond Identity SDK to redeem an otp for a grant code. This function is used in conjunction with authenticateOtp.
Dependencies​
The redeemOtp function requires the Beyond Identity SDK.
- JavaScript
- Kotlin
- Swift
- React Native
- Flutter
yarn add @beyondidentity/bi-sdk-js
or
npm install @beyondidentity/bi-sdk-js
Requirements​
minSdkVersion26 or later.- Apps with Java sources that call the SDK must build with JDK 21. Kotlin-only apps are unaffected.
- Biometric prompts require a
FragmentActivity, such asAppCompatActivity.
Gradle​
To enable the retrieval of Cloudsmith hosted packages via Gradle, we need to add the Cloudsmith repository to
the root/build.gradle file.
repositories {
maven {
url "https://packages.beyondidentity.com/public/bi-sdk-android/maven/"
}
}
After the repository is added, we can specify the Beyond Identity dependencies.
dependencies {
implementation 'com.beyondidentity.android.sdk:embedded:[version]'
}
Requirements​
The SDK supports iOS 15.0 or later.
Swift Package Manager​
From Xcode​
- From the Xcode
Filemenu, selectAdd Packagesand add the following url:
https://github.com/gobeyondidentity/bi-sdk-swift
- Select a version and hit Next.
- Select a target matching the SDK you wish to use.
From Package.swift​
- With Swift Package Manager,
add the following
dependencyto yourPackage.swift:
dependencies: [
.package(url: "https://github.com/gobeyondidentity/bi-sdk-swift.git", from: [version])
]
- Run
swift build
Cocoapods​
Add the pod to your Podfile:
pod 'BeyondIdentityEmbedded'
And then run:
pod install
After installing import with
import BeyondIdentityEmbedded
Using react-native init or an expo app.​
- react-native init
- expo
The SDK requires React Native 0.88.0 or later.
Install the SDK with yarn or npm:
yarn add @beyondidentity/bi-sdk-react-native
npm install @beyondidentity/bi-sdk-react-native
Update native requirements in your ios and android folders:
iOS​
Make sure your ios/Podfile supports "minimum deployment target" 15.1 or later
platform :ios, '15.1'
Navigate to your ios folder and run:
cd ios && pod install
Android​
Make sure your android/build.gradle supports minSdkVersion 26 or later
buildscript {
ext {
minSdkVersion = 26
}
}
Add the following maven url to your repositories in your android/build.gradle
allprojects {
repositories {
maven {
url "https://packages.beyondidentity.com/public/bi-sdk-android/maven/"
}
}
}
For biometric prompts to work on Android, your Activity must extend FragmentActivity. The default ReactActivity already does.
This package requires custom native code and can be used with Development builds or prebuild and cannot be used with Expo Go.
npx expo install @beyondidentity/bi-sdk-react-native
Add the SDK config plugin to the plugins array of your app.{json,config.js,config.ts}:
{
"expo": {
"plugins": [["@beyondidentity/bi-sdk-react-native"]]
}
}
The SDK requires certain minimum native versions. Set these requirments with expo-build-properties.
npx expo install expo-build-properties
{
"expo": {
"plugins": [
["@beyondidentity/bi-sdk-react-native"],
[
"expo-build-properties",
{
"android": {
"minSdkVersion": 26
},
"ios": {
"deploymentTarget": "15.1"
}
}
]
]
}
}
Finally, rebuild your app as described in Expo's Adding custom native code guide.
The SDK requires Flutter 3.44.0 or later.
Pub.Dev​
Add the Beyond Identity Embedded SDK to your dependencies
dependencies:
bi_sdk_flutter: x.y.z
and run an implicit flutter pub get.
Update Android​
Please make sure your android/build.gradle supports minSdkVersion 26 or later.
buildscript {
ext {
minSdkVersion = 26
}
}
For biometric prompts to work on Android, your Activity must extend FragmentActivity. Use FlutterFragmentActivity instead of FlutterActivity:
import io.flutter.embedding.android.FlutterFragmentActivity
class MainActivity : FlutterFragmentActivity()
Update iOS​
Please make sure your project supports "minimum deployment target" 15.1 or later.
In your ios/Podfile set:
platform :ios, '15.1'
Prerequisites​
Before making a call to redeemOtp, you must complete the following prerequisite calls:
- Import the required types and functions from the SDK.
- JavaScript
- Kotlin
- Swift
- React Native
- Flutter
import { Embedded } from '@beyondidentity/bi-sdk-js';
import com.beyondidentity.embedded.sdk.EmbeddedSdk
import BeyondIdentityEmbedded
import { Embedded } from '@beyondidentity/bi-sdk-react-native';
import 'package:bi_sdk_flutter/embeddedsdk.dart';
- Initialize the SDK.
- JavaScript
- Kotlin
- Swift
- React Native
- Flutter
// --- Initialize with required arguments
try {
const embedded = await Embedded.initialize();
console.log("Initialization successful", embedded);
} catch (error) {
console.error("Initialization failed:", error);
}
// --- Initialize with required and optional arguments
const config = {
allowedDomains: ["example.com", "another-example.com"],
logger: function (logType, message) {
console.log(`[${logType}] ${message}`);
},
};
try {
const embedded = await Embedded.initialize(config);
console.log("Initialization successful", embedded);
} catch (error) {
console.error("Initialization failed:", error);
}
// --- Initialize with required arguments
EmbeddedSdk.init(
app = this,
logger = { logMessage ->
Log.d("BeyondIdentityLog", logMessage)
}
)
// --- Initialize with required and optional arguments
EmbeddedSdk.init(
app = this,
biometricAskPrompt = "Please provide your biometric",
logger = { logMessage ->
Log.d("BeyondIdentityLog", logMessage)
},
allowedDomains = listOf("example.com", "another-example.com")
)
// --- Initialize from an Activity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
EmbeddedSdk.init(
app = application,
logger = { logMessage ->
Log.d("BeyondIdentityLog", logMessage)
}
)
// Hand the SDK the Activity that called init()
EmbeddedSdk.setActivity(this)
}
}
// --- Initialize with required arguments
Embedded.initialize(
biometricAskPrompt: "Please provide your biometric"
) { result in
switch result {
case .success():
print("Initialization successful")
case .failure(let error):
print("Initialization failed: \(error)")
}
}
// --- Initialize with required and optional arguments
Embedded.initialize(
allowedDomains: ["example.com", "another-example.com"],
biometricAskPrompt: "Please provide your biometric",
logger: { (logType, message) in
print("\(logType): \(message)")
}
) { result in
switch result {
case .success():
print("Initialization successful")
case .failure(let error):
print("Initialization failed: \(error)")
}
}
// --- Initialize with required arguments
try {
const response = await Embedded.initialize("Please provide your biometric");
console.log(response);
} catch (error) {
console.error("Initialization failed:", error);
}
// --- Initialize with required and optional arguments
try {
const response = await Embedded.initialize(
"Please provide your biometric",
["example.com", "another-example.com"]
);
console.log(response);
Embedded.logEventEmitter.addListener(
"BeyondIdentityLogger",
(message: string) => {
console.log(message);
}
);
} catch (error) {
console.error("Initialization failed:", error);
}
// --- Initialize with required arguments
EmbeddedSdk.initialize('Please provide your biometric');
// --- Initialize with required and optional arguments
EmbeddedSdk.initialize(
'Please provide your biometric',
allowedDomains: ["example.com", "another-example.com"],
logger: EmbeddedSdk.enableLogger(),
).then((_) {
print('Initialization successful');
}).catchError((error) {
print('Initialization failed: $error');
});
-
Use authenticateOtp to initiate authentication using an OTP, and keep the url of the OtpChallengeResponse it returns.
-
Use redeemOtp to redeem the OTP the user received (see example below).
Parameters​
- JavaScript
- Kotlin
- Swift
- React Native
- Flutter
| Parameter | Type | Description |
|---|---|---|
| url | string | Required. The url of the OtpChallengeResponse returned by authenticateOtp, or by a previous failed redeemOtp. |
| otp | string | Required. The OTP to redeem. |
| Parameter | Type | Description |
|---|---|---|
| url | String | Required. The url of the OtpChallengeResponse returned by authenticateOtp, or by a previous failed redeemOtp. |
| otp | String | Required. The OTP to redeem. |
| callback | (Result<RedeemOtpResponse>) -> Unit | Required. Called with the response on success, or a Throwable on failure. |
Alternatively, call the overload that takes a dispatcher instead of a callback. It returns a
Flow that emits the result once it is collected:| Parameter | Type | Description |
|---|---|---|
| url | String | Required. The url of the OtpChallengeResponse returned by authenticateOtp, or by a previous failed redeemOtp. |
| otp | String | Required. The OTP to redeem. |
| dispatcher | CoroutineDispatcher | Optional. The coroutine dispatcher to run on. Defaults to Dispatchers.Default. |
| Parameter | Type | Description |
|---|---|---|
| url | URL | Required. The url of the OtpChallengeResponse returned by authenticateOtp, or by a previous failed redeemOtp. |
| otp | String | Required. The OTP to redeem. |
| callback | @escaping (Result<RedeemOtpResponse, BISDKError>) -> Void | Required. Called with the result. |
The async throws variant takes the same parameters without callback, returns the result directly, and throws a BISDKError on failure.
| Parameter | Type | Description |
|---|---|---|
| url | string | Required. The url of the OtpChallengeResponse returned by authenticateOtp, or by a previous failed redeemOtp. |
| otp | string | Required. The OTP to redeem. |
| Parameter | Type | Description |
|---|---|---|
| url | String | Required. The url of the OtpChallengeResponse returned by authenticateOtp, or by a previous failed redeemOtp. |
| otp | String | Required. The OTP to redeem. |
Returns​
The redeemOtp function returns either an AuthenticateResponse if the OTP was correct, or an OtpChallengeResponse if it was not:
- JavaScript
- Kotlin
- Swift
- React Native
- Flutter
The Promise resolves to an AuthenticateResponse on success, or an OtpChallengeResponse if the OTP was wrong.
sealed class RedeemOtpResponse {
data class Success(val authenticateResponse: AuthenticateResponse) : RedeemOtpResponse()
data class FailedOtp(val otpChallengeResponse: OtpChallengeResponse) : RedeemOtpResponse()
}
public enum RedeemOtpResponse: Equatable, Hashable {
case success(AuthenticateResponse)
case failedOtp(OtpChallengeResponse)
}
redeemOtp(url: string, otp: string): Promise<AuthenticateResponse | OtpChallengeResponse>
Check for redirectUrl in the response to tell the two apart.
class RedeemOtpResponse {
final AuthenticateResponse? success;
final OtpChallengeResponse? failedOtp;
bool get isSuccess;
bool get isFailedOtp;
}
On Kotlin, the result is delivered to the callback, or emitted by the returned Flow. On Swift, it is delivered to the callback, or returned by the async throws variant. On JavaScript, React Native and Flutter, the function returns a Promise or Future.
On success, the AuthenticateResponse contains the following keys:
-
redirectUrl: string containing the redirect URL that originates from the /authorize call's
redirect_uriparameter. The OAuth2 authorizationcodeand thestateparameter of the /authorize call are attached with the "code" and "state" parameters to this URL. -
message: optional string containing a displayable message defined by policy returned by the cloud on success.
-
passkeyBindingToken: string containing a one-time-token that may be redeemed for a CredentialBindingLink.
You can exchange the token for a link by calling the credential-binding-jobs endpoint.
const response = await fetch(
`https://auth-${region}.beyondidentity.com/v1/tenants/${tenantId}/realms/${realmId}/applications/${applicationId}/credential-binding-jobs`,
{
method: "POST",
headers: { Authorization: `Bearer ${passkeyBindingToken}` },
}
);
This response will contain a credential_binding_link, which can be used by isBindPasskeyUrl and bindPasskey to bind the credential.
If the OTP was wrong, the OtpChallengeResponse contains the following key:
- url: a URL containing the state of the authentication. Use it when calling redeemOtp or authenticateOtp again.
Examples​
Example: Call redeemOtp​
- JavaScript
- Kotlin
- Swift
- React Native
- Flutter
let response = await embedded.redeemOtp(url, otp);
import com.beyondidentity.embedded.sdk.EmbeddedSdk
import com.beyondidentity.embedded.sdk.models.RedeemOtpResponse
EmbeddedSdk.redeemOtp(url, otp) { result ->
result.onSuccess { response ->
when (response) {
is RedeemOtpResponse.Success ->
print("Authenticated. Redirect to ${response.authenticateResponse.redirectUrl}")
is RedeemOtpResponse.FailedOtp ->
print("Incorrect OTP. Retry with ${response.otpChallengeResponse.url}")
}
}
result.onFailure { e ->
print("Error redeeming OTP: $e")
}
}
Embedded.shared.redeemOtp(url: url, otp: otp) { result in
switch result {
case .success(.success(let authenticateResponse)):
print("Authenticated. Redirect to \(authenticateResponse.redirectUrl)")
case .success(.failedOtp(let otpChallengeResponse)):
print("Incorrect OTP. Retry with \(otpChallengeResponse.url)")
case .failure(let error):
print("Error redeeming OTP: \(error.localizedDescription)")
}
}
const response = await Embedded.redeemOtp(url, otp);
if ("redirectUrl" in response) {
console.log("Authenticated. Redirect to", response.redirectUrl);
} else {
console.log("Incorrect OTP. Retry with", response.url);
}
RedeemOtpResponse response = await EmbeddedSdk.redeemOtp(url, otp);
if (response.isSuccess) {
print("Authenticated. Redirect to ${response.success!.redirectUrl}");
} else if (response.isFailedOtp) {
print("Incorrect OTP. Retry with ${response.failedOtp!.url}");
}