The Descope SDK for for Android provides convenient access to the Descope user management and authentication APIs for applications written for Android. You can read more on the Descope Website.
Add the following to your build.gradle
dependencies:
implementation 'com.descope:descope-kotlin:0.11.1'
A Descope Project ID
is required to initialize the SDK. Find it
on the project page in
the Descope Console.
import com.descope.Descope
// Application on create
override fun onCreate() {
Descope.setup(this, projectId = "<Your-Project-Id>")
// Optionally, you can configure your SDK to your needs
Descope.setup(this, projectId = "<Your-Project-Id>") {
// set a custom base URL (needs to be set up in the Descope console)
baseUrl = "https://my.app.com"
// enable the logger
if (BuildConfig.DEBUG) {
logger = DescopeLogger()
}
}
}
Authenticate the user in your application by starting one of the authentication methods. For example, let's use OTP via email:
// sends an OTP code to the given email address
Descope.otp.signUp(method = DeliveryMethod.Email, loginId = "[email protected]")
Finish the authentication by verifying the OTP code the user entered:
// if the user entered the right code the authentication is successful
val authResponse = Descope.otp.verify(
method = DeliveryMethod.Email,
loginId = "[email protected]",
code = code
)
// we create a DescopeSession object that represents an authenticated user session
val session = DescopeSession(authResponse)
// the session manager automatically takes care of persisting the session
// and refreshing it as needed
Descope.sessionManager.manageSession(session)
On the next application launch check if there's a logged in user to decide which screen to show:
// check if we have a valid session from a previous launch and that it hasn't expired yet
if (Descope.sessionManager.session?.refreshToken?.isExpired == true) {
// Show main UI
} else {
// Show login UI
}
Use the active session to authenticate outgoing API requests to the application's backend:
val connection = url.openConnection() as HttpsURLConnection
connection.setAuthorization(Descope.sessionManager)
The DescopeSessionManager
class is used to manage an authenticated
user session for an application.
The session manager takes care of loading and saving the session as well
as ensuring that it's refreshed when needed. For the default instances of
the DescopeSessionManager
class this means using the EncryptedSharedPreferences
for secure storage of the session and refreshing it a short while before it expires.
Make sure you initialize Descope with your application context so that the session manager implementation can access Android storage and load any existing session and user data:
Descope.setup(applicationContext, projectId = "<PROJECT-ID>")
Once the user completes a sign in flow successfully you should set the
DescopeSession
object as the active session of the session manager.
val authResponse = Descope.otp.verify(DeliverMethod.Email, "[email protected]", "123456")
val session = DescopeSession(authResponse)
Descope.sessionManager.manageSession(session)
The session manager can then be used at any time to ensure the session is valid and to authenticate outgoing requests to your backend with a bearer token authorization header.
val connection = url.openConnection() as HttpsURLConnection
connection.setAuthorization(Descope.sessionManager)
If your backend uses a different authorization mechanism you can of course
use the session JWT directly instead of the extension function. You can either
add another extension function on URLRequest
such as the one above, or you
can do the following.
Descope.sessionManager.refreshSessionIfNeeded()
Descope.sessionManager.session?.sessionJwt?.apply {
connection.setRequestProperty("X-Auth-Token", this)
} ?: throw ServerError.unauthorized
When the application is relaunched the DescopeSessionManager
loads any
existing session automatically, so you can check straight away if there's
an authenticated user.
// Application class onCreate
override fun onCreate() {
super.onCreate()
Descope.setup(this, projectId = "<Your-Project-Id>")
Descope.sessionManager.session?.run {
print("User is logged in: $this")
}
}
When the user wants to sign out of the application we revoke the active session and clear it from the session manager:
Descope.sessionManager.session?.refreshJwt?.run {
Descope.auth.logout(this)
Descope.sessionManager.clearSession()
}
You can customize how the DescopeSessionManager
behaves by using
your own storage
and lifecycle
objects. See the documentation
for more details.
We can authenticate users by building and running Flows. Flows are built in the Descope flow editor. The editor allows you to easily define both the behavior and the UI that take the user through their authentication journey. Read more about it in the Descope getting started guide.
Before we can run a flow, it must first be defined and hosted. Every project comes with predefined flows out of the box. You can customize your flows to suit your needs and host it. Follow the getting started guide for more details.
Some authentication methods rely on leaving the application's context to authenticate the user, such as navigating to an identity provider's website to perform OAuth (social) authentication, or receiving a Magic Link via email or text message. If you do not intend to use these authentication methods, you can skip this step. Otherwise, in order for the user to get back to your application, setting up App Links is required. Once you have a domain set up and verified for sending App Links, you'll need to handle the incoming deep links in your app, and resume the flow:
Any activity can handle an incoming App Link, however in order to resume the flow, the DescopeFlowView
used to run the flow must be called with the resumeFromDeepLink()
function.
this code example demonstrates how app links can be handled - you're app architecture might differ'
class FlowRedirectActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// assuming descopeFlowView is a reference to your instance of DescopeFlowView
intent?.data?.run {
descopeFlowView.resumeFromDeepLink(this)
}
}
// alternatively you might receive the URI from another activity
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
intent?.getStringExtra(descopeFlowUri)?.run {
// assuming descopeFlowView is a reference to your instance of DescopeFlowView
descopeFlowView.resumeFromDeepLink(Uri.parse(this))
}
}
}
<activity
android:name=".FlowRedirectActivity"
android:exported="true"> <!-- exported required for app links -->
<intent-filter android:autoVerify="true"> <!-- autoVerify required for app links -->
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<!-- replace with your host, the path can change must must be reflected when running the flow -->
<data android:scheme="https" android:host="<YOUR_HOST_HERE>" android:path="/done" />
</intent-filter>
<!-- Optional: App Links are blocked by default on Opera and some other browsers. Add a custom scheme for that use case specifically -->
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<!-- replace with something unique. this will only be used as a backup for Opera users. -->
<data android:scheme="myapp" android:host="auth" />
</intent-filter>
</activity>
After completing the prerequisite steps, it is now possible to run a flow.
The flow will run in a dedicated DescopeFlowView
which receives a DescopeFlow
object. The DescopeFlow
objects defines all of the options available when running a flow.
Read the class documentation for a detailed explanation. The flow needs to reside in your UI in
some form, and to start it, call the run()
function
val descopeFlow = DescopeFlow(Uri.parse("<URL_FOR_FLOW_IN_SETUP_#1>"))
descopeFlow.lifecycle = object : DescopeFlow.LifeCycle {
override fun onReady() {
// present the flow view via animation, or however you see fit
}
override fun onSuccess(response: AuthenticationResponse) {
// optionally hide the flow UI
// manage the incoming session
Descope.sessionManager.manageSession(DescopeSession(response))
// launch the "logged in" UI of your app
}
override fun onError(exception: DescopeException) {
// handle any errors here
}
override fun onNavigation(uri: Uri): Flow.NavigationStrategy {
// manage navigation event by deciding whether to open the URI
// in a custom tab (default behavior), inline, or do nothing.
}
}
// set the OAuth provider ID that is configured to "sign in with Google"
descopeFlow.oauthProvider = OAuthProvider.Google
// set the oauth redirect URI to use your app's deep link
descopeFlow.oauthRedirect = "<URL_FOR_APP_LINK_IN_SETUP_#2>"
// customize the flow presentation further
descopeFlow.presentation = flowPresentation
// run the flow
descopeFlowView.run(descopeFlow)
We can authenticate users by using any combination of the authentication methods supported by this SDK. Here are some examples for how to authenticate users:
Send a user a one-time password (OTP) using your preferred delivery method (email / SMS). An email address or phone number must be provided accordingly.
The user can either sign up
, sign in
or sign up or in
// Every user must have a loginId. All other user details are optional:
Descope.otp.signUp(
DeliveryMethod.Email, "[email protected]", SignUpDetails(
name = "Andy Rhoads"
)
)
The user will receive a code using the selected delivery method. Verify that code using:
val authResponse = Descope.otp.verify(DeliveryMethod.Email, "[email protected]", "123456")
Send a user a Magic Link using your preferred delivery method (email / SMS). The Magic Link will redirect the user to page where the its token needs to be verified. This redirection can be configured in code, or globally in the Descope Console
The user can either sign up
, sign in
or sign up or in
// If configured globally, the redirect URI is optional. If provided however, it will be used
// instead of any global configuration
Descope.magiclink.signUp(DeliveryMethod.Email, "[email protected]")
To verify a magic link, your redirect page must call the validation function
on the token (t
) parameter (https://your-redirect-address.com/verify?t=<token>
):
val authResponse = Descope.magiclink.verify("<token>")
Users can authenticate using their social logins, using the OAuth protocol. Configure your OAuth settings on the Descope console. To start a flow call:
// Choose an oauth provider out of the supported providers
// If configured globally, the redirect URL is optional. If provided however, it will be used
// instead of any global configuration.
// Redirect the user to the returned URL to start the OAuth redirect chain
val authURL = Descope.oauth.signUpOrIn(OAuthProvider.Github, redirectUrl = "exampleauthschema://my-app.com/handle-oauth")
Take the generated URL and authenticate the user using Chrome Custom Tabs
The user will authenticate with the authentication provider, and will be
redirected back to the redirect URL, with an appended code
HTTP URL parameter.
Exchange it to validate the user:
// Catch the redirect using a dedicated deep link Activity
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val incomingUri: Uri = intent?.data ?: return
val code = incomingUri.getQueryParameter("code")
GlobalScope.launch {
// Exchange code for session
val authResponse = Descope.oauth.exchange(code)
val session = DescopeSession(authResponse)
Descope.sessionManager.manageSession(session)
}
}
Users can authenticate to a specific tenant using SAML or Single Sign On. Configure your SSO/SAML settings on the Descope console. To start a flow call:
// Choose which tenant to log into
// If configured globally, the return URL is optional. If provided however, it will be used
// instead of any global configuration.
// Redirect the user to the returned URL to start the SSO/SAML redirect chain
val authURL = Descope.sso.start(emailOrTenantId = "my-tenant-ID", redirectUrl = "exampleauthschema://my-app.com/handle-saml")
Take the generated URL and authenticate the user using Chrome Custom Tabs
The user will authenticate with the authentication provider, and will be
redirected back to the redirect URL, with an appended code
HTTP URL parameter.
Exchange it to validate the user:
// Catch the redirect using a dedicated deep link Activity
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val incomingUri: Uri = intent?.data ?: return
val code = incomingUri.getQueryParameter("code")
GlobalScope.launch {
// Exchange code for session
val authResponse = Descope.sso.exchange(code)
val session = DescopeSession(authResponse)
Descope.sessionManager.manageSession(session)
}
}
Users can authenticate by creating or using a passkey. Configure your Passkey/WebAuthn settings on the Descope console. Make sure it is enabled and that the top level domain is configured correctly. After that, go through the Add support for Digital Asset Links setup, as described in the official Google docs, and complete the asset links and manifest preparations.
Note: The passkey operations are all suspending functions that perform network requests before and after displaying the modal authentication view. It is thus recommended to switch the user interface to a loading state before calling them, otherwise the user might accidentally interact with the app when the authentication view is not being displayed.
// Enter loading state...
val authResponse = Descope.passkey.signUpOrIn(this@MyActivity, loginId)
val session = DescopeSession(authResponse)
Descope.sessionManager.manageSession(session)
// Exit loading state...
The user can authenticate using an authenticator app, such as Google Authenticator.
Sign up like you would using any other authentication method. The sign up response
will then contain a QR code image
that can be displayed to the user to scan using
their mobile device camera app, or the user can enter the key
manually or click
on the link provided by the provisioningURL
.
Existing users can add TOTP using the update
function.
// Every user must have a loginId. All other user information is optional
val totpResponse = Descope.totp.signUp(loginId = "[email protected]")
// Use one of the provided options to have the user add their credentials to the authenticator
// totpResponse.provisioningURL
// totpResponse.image
// totpResponse.key
There are 3 different ways to allow the user to save their credentials in their authenticator app - either by clicking the provisioning URL, scanning the QR image or inserting the key manually. After that, signing in is done using the code the app produces.
val authResponse = Descope.totp.verify(loginId = "[email protected]", code = "987654")
Authenticate users using a password.
To create a new user that can later sign in with a password:
val authResponse = Descope.password.signUp(
"[email protected]",
"securePassword123!",
SignUpDetails(
name = "Andy Rhoads"
)
)
Authenticate an existing user using a password:
val authResponse = Descope.password.signIn(
"[email protected]",
"securePassword123!"
)
If you need to update a user's password:
Descope.password.update(
"[email protected]",
"newSecurePassword456!",
"user-refresh-jwt"
)
To replace a user's password by providing their current password:
val authResponse = Descope.password.replace(
"[email protected]",
"securePassword123!",
"newSecurePassword456!"
)
Initiate a password reset by sending an email:
Descope.password.sendReset(
"[email protected]",
"exampleauthschema://my-app.com/handle-reset"
)
To learn more please see the Descope Documentation and API reference page.
If you need help you can email Descope Support
The Descope SDK for Flutter is licensed for use under the terms and conditions of the MIT license Agreement.