
Okta Mobile Kotlin
”Make the easy things simple and make the hard things possible.”
The Okta Mobile SDKs are a suite of libraries that intends to replace our legacy mobile SDKs, with the aim to streamline development, ease maintenance and feature development, and enable new use cases that were previously difficult or impractical to implement. We are building a platform to support the development of many SDKs, allowing application developers to choose which SDKs they need.
The Okta Mobile Kotlin SDK is a Kotlin Multiplatform (KMP) library targeting Android and JVM, with select modules supporting JS and WASM.
SDK Overview
This SDK consists of several different libraries, each with detailed documentation.
Support Policy
Legacy okta-oidc-android support
We intend to support okta-oidc-android with critical bug and security fixes for the foreseeable future. Once the Kotlin Mobile SDK is generally available, all new features will be built on top of okta-mobile-kotlin and will replace okta-oidc-android.
Unlocking use cases
Okta is busy adding new functionality to its identity platform. We're excited to unlock these new capabilities for Android. These SDKs are built on top of Kotlin, Kotlin Coroutines, and OkHttp. We are doubling down on our developer experience, providing seamless ways to log in, store, and access OAuth tokens. We are building an initial set of functionality unlocking new OAuth flows that were not possible before, including:
Installation
Add the Okta Mobile Kotlin dependencies to your build.gradle file:
// Ensure all dependencies are compatible using the Bill of Materials (BOM).
implementation(platform('com.okta.kotlin:bom:2.0.3'))
// Add the dependencies to your project.
implementation('com.okta.kotlin:auth-foundation')
implementation('com.okta.kotlin:oauth2')
implementation('com.okta.kotlin:web-authentication-ui')
See the CHANGELOG for the most recent changes.
If you're migrating from okta-oidc-android see migrate.md for more information.
Okta Mobile SDK for Kotlin
Release status
This library uses semantic versioning and follows Okta's Library Version Policy.
The latest release can always be found on the releases page.
Need help?
If you run into problems using the SDK, you can:
- Ask questions on the Okta Developer Forums
- Post issues here on GitHub (for code errors)
Getting Started
To get started, you will need:
- An Okta account, called an organization (sign up for a free developer organization if you need one).
- An Okta Application, configured as a Native App. This is done from the Okta Developer Console. When following the wizard, use the default properties. They are designed to work with our sample applications.
- Android Studio
Usage Guide
This SDK consists of several different libraries, each with their own detailed documentation.
SDKs are split between two primary use cases:
- Minting tokens (authentication)
- Okta supports many OAuth flows, our Android SDKs support the following: Authorization Code, Interaction Code, Refresh Token, Resource Owner Password, Device Authorization, and Token Exchange.
- Managing the token lifecycle (refresh, storage, validation, etc)
Auto backup rules
This SDK uses on-device encryption keys to store data. Because of this, the SDK files should not be backed up. This SDK provides backup rules to exclude files automatically.
But, if your application provides its own backup rules by specifying android:dataExtractionRules or android:fullBackupContent, please include SDK backup rules as specified in data_extraction_rules and full_backup_content.
Kotlin Coroutines
Kotlin Coroutines are used extensively throughout the SDKs. All methods can be used via any thread (including the main thread), and will switch to a background thread internally when performing network IO or expensive computation.
Web Authentication using OIDC redirect
The simplest way to integrate authentication in your app is with OIDC through a web browser, using the Authorization Code Flow grant.
Configure your OAuth Settings
Before authenticating your user, you need to set your default OidcConfiguration using the settings defined in your application in the Okta Developer Console.
import android.content.Context
import com.okta.authfoundation.AuthFoundation
import com.okta.authfoundation.client.OidcConfiguration
val context: Context = TODO("Supplied by the developer.")
AuthFoundation.initializeAndroidContext(context)
OidcConfiguration.default = OidcConfiguration(
clientId = "{clientId}",
defaultScope = "openid email profile offline_access",
issuer = "https://{yourOktaOrg}.okta.com/oauth2/default"
)
Create a Web Authentication Client
We will create a WebAuthentication and use it to perform authentication.
This launches a Chrome Custom Tab to display the login form, and once complete, redirects back to the application.
import android.content.Context
import com.okta.authfoundation.credential.Credential
import com.okta.oauth2.AuthorizationCodeFlow
com.okta.webauthenticationui.WebAuthentication
context: Context = TODO()
credential: Credential
redirectUrl: String = TODO()
auth = WebAuthentication()
( result = auth.login(context, redirectUrl)) {
OAuth2ClientResult.Error -> {
}
OAuth2ClientResult.Success -> {
credential = Credential.store(token = result.result)
Credential.setDefaultCredential(credential)
}
}
Next we need to be sure our application handles the redirect. Add the following snippet to your build.gradle:
Note: you will need to replace the {redirectUriScheme} with your applications redirect scheme. For example, a signInRedirectUri of com.okta.sample.android:/login would mean replacing {redirectUriScheme} with com.okta.sample.android.
android {
defaultConfig {
manifestPlaceholders = [
"webAuthenticationRedirectScheme": "{redirectUriScheme}"
]
}
}
Device Authorization Flow
DeviceAuthorizationFlow can be used to perform OAuth 2.0 Device Authorization Grant.
The Device Authorization Flow is designed for Internet connected devices that either lack a browser to perform a user-agent based authorization or are input constrained to the extent that requiring the user to input text in order to authenticate during the authorization flow is impractical.
Token Exchange Flow
TokenExchangeFlow can be used to perform OIDC Native SSO.
The Token Exchange Flow exchanges an ID Token and a Device Secret for a new set of tokens.
import com.okta.authfoundation.client.OAuth2Client
import com.okta.authfoundation.credential.Credential
import com.okta.oauth2.TokenExchangeFlow
val tokenExchangeFlow = TokenExchangeFlow()
when (val result = tokenExchangeFlow.start(idToken, deviceSecret)) {
is OAuth2ClientResult.Error -> {
}
is OAuth2ClientResult.Success -> {
tokenExchangeCredential = Credential.store(result.result)
}
}
Note: You'll want to ensure you have 2 DIFFERENT Credentials. The first needs to have the idToken, and deviceSecret minted via a WebAuthenticationClient. The second will be used in the TokenExchangeFlow.
Logout
There are multiple terms that might be confused when logging a user out.
Using a Credential to determine user authentication status
There are a few options to determine the status of a user authentication. Each option has unique pros and cons and should be chosen based on the needs of your use case.
- Non null default credential:
Credential.default != null
- Non empty credential allIds:
Credential.allIds.isNotEmpty()
- getValidAccessToken:
Credential.default?.getValidAccessToken() != null
- Custom implementation:
Credential.default?.token, Credential.default?.refresh(), and
Details on each approach are below.
Determine authentication status via non null Credential
Credentials require a Token. If there are no Credentials present, then no Token has been stored. Note that Credential.default can throw a BiometricInvocationException if the Credential was stored using .
Determine authentication by checking if any Credentials exist
Credential.allIds lists list of all ids of stored Credentials. If it returns an empty list, there are no stored Credentials.
Determine authentication status via getValidAccessToken
Credential has a method called getValidAccessToken which checks to see if the credential has a token, and has a valid access token. If the access token is expired, and a refresh token exists, a refresh is implicitly called on the Credential. If the implicit refresh is successful, getValidAccessToken returns the new access token. There are two main down sides to this approach. First, it's a and could make network calls. Second, the failure is not returned, an error could occur due to a network error, a missing token, a missing refresh token, or a configuration error.
Determine authentication status via custom implementation
If your use case requires insight into errors and the current state of the Credential, you can use implement it to your needs with the primitives Credential provides. See the documentation for the associated properties and methods: Credential.token, Credential.refresh(), Credential.getAccessTokenIfValid().
Biometric Credentials
The SDK has built-in support for handling Biometric encryption. To set the default token encryption as Biometric, Credential.Security.standard can be set to Credential.Security.BiometricStrong or Credential.Security.BiometricStrongOrDeviceCredential. Biometric encryption also requires setting Credential.Security.promptInfo.
Notes:
- The SDK does not check which biometrics are enrolled on the user's device. Please check this using https://developer.android.com/reference/android/hardware/biometrics/BiometricManager#canAuthenticate(int) before setting the appropriate security level
- The SDK automatically deletes Token entries stored using invalidated biometric keys.
- Biometric Credentials should only be fetched using async APIs in class, otherwise will be thrown.
Setting Biometric security for new Credentials globally
Credential.Security.standard = Credential.Security.BiometricStrong()
Credential.Security.promptInfo = BiometricPrompt.PromptInfo.Builder()
.setTitle("Title")
.setNegativeButtonText("Cancel Button")
.setAllowedAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG)
.build()
Setting Biometric security for a single Credential
val token = TODO("Supplied by user")
val credential = Credential.store(token, security = Credential.Security.BiometricStrong())
Auth-per-use Biometric keys
The SDK uses Biometric keys with a timeout of 5 seconds by default. This allows apps to invoke Biometrics once, and perform operations on multiple Biometric Credentials. Auth-per-use Biometric Credentials are also supported using the following:
Credential.Security.standard = Credential.Security.BiometricStrong(userAuthenticationTimeout = 0)
val token = TODO("Supplied by user")
val credential = Credential.store(token, security = Credential.Security.BiometricStrong(userAuthenticationTimeout = 0))
Biometric exceptions
Android BiometricPrompt can fail due to AuthenticationCallback.onAuthenticationFailed and AuthenticationCallback.onAuthenticationError. See this relevant Android developer doc: BiometricPrompt.AuthenticationCallback
AuthenticationCallback.onAuthenticationError can return error codes to recover from different Biometric situations, as listed here: https://developer.android.com/reference/kotlin/androidx/biometric/BiometricPrompt#ERROR_CANCELED()
When using Biometric security, Credential fetching functions can throw BiometricAuthenticationException, and the relevant errors can be queried as follows:
val credential = try {
Credential.getDefaultAsync()
} catch (ex: BiometricAuthenticationException) {
when (val details = ex.biometricExceptionDetails) {
is BiometricExceptionDetails.OnAuthenticationFailed -> {
TODO("onAuthenticationFailed has no error codes or messages")
}
is BiometricExceptionDetails.OnAuthenticationError -> {
val errorMessage = details.errString
val errorCode = details.errorCode
}
}
}
Networking customization
The Okta Mobile Kotlin SDKs should provide all the required networking by default, however, if you would like to customize networking
behavior, that is also possible.
The SDK uses OkHttp as the API for performing network requests.
The SDK also uses OkHttp as the default implementation for performing network requests.
If you intent to customize networking behavior, there are a few options:
- Add an Interceptor to the
OkHttpClient you provide to
AuthFoundationDefaults.okHttpClientFactory
- Return a custom implementation of
Call.Factory when initializing the SDK in AuthFoundationDefaults.okHttpClientFactory
OkHttp Interceptor
Configuring the OkHttpClient with an Interceptor is the recommend approach to customizing the networking behavior.
Adding an interceptor allows you to listen for requests and responses, customize requests before they are sent, and customize responses
before they are processed by the SDK.
Custom Call Factory
Providing a custom call factory is an advanced use case, and is not recommended. The possibilities are endless, including the ability to
replace the engine that executes the HTTP requests.
Rate Limit Handling
The Okta API will return 429 responses if too many requests are made within a given time. Please see Rate Limiting at Okta for a complete
list of which endpoints are rate limited. This SDK automatically retries requests on 429 errors. The default configuration is as follows:
| Configuration Option | Description |
|---|
| maxRetries | The number of times to retry. The default value is 3. |
| minDelaySeconds | The minimum amount of time to wait between each retry. The default value is second. |
Configuring retry parameters
To configure retry parameters, an EventHandler must be registered before creating an OidcConfiguration. In the EventHandler,
RateLimitExceededEvent events will be emitted any time a request receives a response with 429 status code. minDelaySeconds and
maxRetries can be adjusted based on details provided by the event.
Migrating from okta-mobile-kotlin 1.x to 2.x
Token migration
The process for Token migration varies based on use of custom TokenStorage or encryption spec when creating CredentialDataSource in 1.x. Token migration is handled automatically in the simplest case without user intervention:
client.createCredentialDataSource(context)
Migration with custom KeyGenParameterSpec
1.x:
val keyGenParameterSpec: KeyGenParameterSpec = TODO("Supplied by user")
client.createCredentialDataSource(context, keyGenParameterSpec)
2.x:
val keyGenParameterSpec: KeyGenParameterSpec = TODO("Supplied by user")
V1ToV2StorageMigrator.legacyKeyGenParameterSpec = keyGenParameterSpec
Migration with custom TokenStorage
1.x:
val customTokenStorage: TokenStorage = TODO("Supplied by user")
client.createCredentialDataSource(customTokenStorage)
2.x:
val legacyTokenStorage: LegacyTokenStorage = TODO("Supplied by user")
V1ToV2StorageMigrator.legacyStorage = legacyTokenStorage
API migration
Credential changes
CredentialBootstrap, CredentialDataSource, and Credential contain several changes over 1.x. s can no longer contain a null . Because of this change from 1.x, the flow for creating without , followed by calling can no longer be used.
When creating a new with , a must be provided.
1.x would create a new Credential with null Token if no default existed when calling . In 2.x, default can be fetched using or . Both of those have a type of instead of , and return if no default exists.
1.x contained Credential handling APIs in CredentialBootstrap and CredentialDataSource. All Credential management calls have been moved to Credential in 2.x. CredentialBootstrap has been deleted, and CredentialDataSource is private in 2.x.
1.x provided suspend functions for handling creation and management of any Credentials. 2.x provides synchronous Credential management functions in addition to suspend functions.
Initialization changes
The SDK initialization calls in 1.x were as follows:
val context: Context = TODO("Supplied by the developer.")
val oidcConfiguration = OidcConfiguration(
clientId = "{clientId}",
defaultScope = "openid email profile offline_access",
)
val client = OidcClient.createFromDiscoveryUrl(
oidcConfiguration,
"https://{yourOktaOrg}.okta.com/oauth2/default/.well-known/openid-configuration".toHttpUrl(),
)
CredentialBootstrap.initialize(client.createCredentialDataSource(context))
In 2.x, this is changed to:
val context: Context = TODO("Supplied by the developer.")
AuthFoundation.initializeAndroidContext(context)
OidcConfiguration.default = OidcConfiguration(
clientId = "{clientId}",
defaultScope = "openid email profile offline_access",
issuer = "https://{yourOktaOrg}.okta.com/oauth2/default"
)
OAuth flows
In 1.x, OAuth flows were created as follows:
val oauthFlow = CredentialBootstrap.oidcClient.createWebAuthenticationClient()
In 2.x, this has been changed to:
val oauthFlow = WebAuthentication()
By default, all OAuth flows use OAuth2Client associated with OidcConfiguration.default. Custom OAuth2Client or OidcConfiguration can be passed into OAuth flows as follows:
val oidcConfiguration: OidcConfiguration = TODO("Supplied by user")
val oauthFlow = WebAuthentication(oidcConfiguration)
val client: OAuth2Client = TODO("Supplied by user")
val oauthFlow = WebAuthentication(client)
WebAuthenticationUi
WebAuthenticationClient has been renamed to WebAuthentication.
Troubleshooting
- java.lang.NoClassDefFoundError: Failed resolution of: Ljava/time/Instant;
FlowCancelledException
FlowCancelledException is supposed to be thrown in cases where the user has decided to cancel the login flow, usually by quitting the browser login window. It can sometimes be incorrectly thrown in the following cases:
- Using the Android system webview while logging out. The webview doesn't store the session after a successful login, so logging out never redirects, and the user is forced to cancel logout process
- Deleting the browser cache after logging in, then attempting to log out. Similar to the above, it is important for browser to store the login state to logout successfully, otherwise the browser can not provide the logout redirect.
- Browser providing empty redirect results, followed by well-defined results. This has been observed in some older devices and browsers. This problem can be worked around by setting AuthFoundationDefaults.loginCancellationDebounceTime
Running the sample
The sample is designed to show what is possible when using the SDK.
Configuring the sample
Update the okta.properties file in the root directory of the project with the contents created from the Okta admin dashboard:
issuer=https://YOUR_ORG.okta.com/oauth2/default
clientId=test-client-id
signInRedirectUri=com.okta.sample.android:/login
signOutRedirectUri=com.okta.sample.android:/logout
legacySignInRedirectUri=com.okta.sample.android.legacy:/login
legacySignOutRedirectUri=com.okta.sample.android.legacy:/logout
Notes:
- issuer - is your authorization server, usually https://your_okta_domain.okta.com/oauth2/default, but custom authorization servers are supported. See https://your_okta_domain.okta.com/admin/oauth2/as for available authorization servers.
- clientId - is your applications client id, created in your Okta admin dashboard
Launching the sample
You can open this sample in Android Studio or build it using Gradle.
./gradlew :app:assembleDebug
Contributing
We are happy to accept contributions and PRs! Please see the contribution guide to understand how to structure a contribution.