Kotlin Quickstart

This guide will only include the frontend integration. If you would like to also handle Session Management in your backend, select your backend technology below:


This is a quickstart guide to help you integrate Descope with your Kotlin application. Follow the steps below to get started.

Add the Descope Package

Next, we need to add the Descope Kotlin SDK as a dependency.

  1. Within Android Studio, go to File > Project Structure > Dependencies > Add Dependency > Library Dependency
  2. Search for the dependency: "com.descope"
  3. Configure your desired dependency rules
  4. Click "Ok"

Import the Kotlin SDK

Next step is to import the Descope Kotlin dependency

MainActivity.kt
// ...
import com.example.kotlinsampleapp.util.supportWideScreen
import androidx.compose.runtime.getValue
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import com.descope.Descope // <-- Import the Descope SDK
 
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
 
        setContent {
            WelcomeScreen()
        }
    }
}

Configure Descope with a custom Project ID

Configure Descope in the MainActivity class. A Descope Project ID is required to initialize the SDK. You can find this ID on the project page in the Descope Console.

Note

You can also add the optional baseUrl parameter if you're utilizing a CNAME within your Descope project (ex: https://auth.company.com).

MainActivity.kt
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Descope.setup(this, projectId = "__ProjectID__") // <-- Configure Descope with your Project ID
        setContent {
            WelcomeScreen()
        }
    }
}

Define and host your flow

Before we can run a flow, it must first be defined and hosted. Every project comes with predefined flows out of the box, found in your Descope console. You can customize your flows to suit your needs and host it. Essentially, you'll need the URL where your authentication flow is separately hosted on the web (eg. https://example.com/login).

Running a flow via the Kotlin SDK requires setting up App Links. This is essential for the SDK to be notified when the user has successfully authenticated using a flow. 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: Define an Activity to handle the App Link sent at the end of a flow

FlowDoneActivity.kt
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.descope.Descope
import com.descope.session.DescopeSession
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
 
class FlowDoneActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val incomingUri: Uri = intent?.data ?: return // The incoming App link
 
        // `exchange` is a suspended function.
        // Use whichever scope makes sense in your app or keep the global scope
        GlobalScope.launch(Dispatchers.Main) {
            try {
                // exchange the incoming URI for a session
                val authResponse = Descope.flow.currentRunner?.exchange(incomingUri) ?: throw Exception("Flow is not running")
                val session = DescopeSession(authResponse)
                Descope.sessionManager.manageSession(session)
 
                // Show the post-authentication screen, for example
                startActivity(Intent(this@FlowDoneActivity, MainActivity::class.java).apply {
                    flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
                })
            } catch (e: Exception) {
                // Handle errors here
            }
            finish() // There's no UI for this Activity, it just handles the logic
        }
    }
}

Add a matching Manifest declaration

In your AndroidManifest.xml, add a Manifest declaration that matches the FlowDoneActivity you just defined. You'll also need to add the URL where you hosted your flow.

Note

If you need to support Magic Link redirects, follow the steps in our README.

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyApplication"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:label="@string/app_name"
            android:theme="@style/Theme.KotlinSampleApp">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
		<!-- Activity Start -->
       <activity
           android:name=".FlowDoneActivity"
           android:launchMode="singleTop"
           android:theme="@style/Theme.AppCompat.Light.NoActionBar"
           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_flow_url_host>_url" android:path="/done" />
           </intent-filter>
       </activity>
		<!-- Activity End -->
    </application>
</manifest>

Run your Flow

The 'createFlow' function starts the authentication process with a custom flow (url from step 4) and deep link url (url from step 5).

MainActivity.kt
@Composable
fun StartFlow(context: Context, modifier: Modifier = Modifier) {
    
    Column(modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally) {
        Text(
            text = "Welcome",
            style = MaterialTheme.typography.bodyMedium,
            textAlign = TextAlign.Center,
            modifier = Modifier.padding(top = 64.dp, bottom = 12.dp)
        )
        Button(
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 28.dp, bottom = 1.dp),
            onClick = {
                try {
                    Descope.flow.create(
                        flowUrl = "https://auth.descope.io/login/__ProjectID__", // <-- Replace with your flow URL
                        deepLinkUrl = "<your_deep_link_url>", // <-- Replace with your deep link URL
                    ).start(context)
                } catch (e: Exception) {
                    Log.e("ERROR", e.stackTraceToString())
                }
            },
            ) {
            Text(text = "Start flow")
        }
        if (getUserEmail() !== null) {
            Text(
                text = getUserEmail() ?: ""
            )
        } else {
            Text(text = "No email found")
        }
    }
}

Utilize the Kotlin SDK Session Management Functions

Descope provides the sessionManager to check if the user is authenticated or get user data such as email, userId, etc. You can use these to customize the user experience:

  • isAuthenticated - is user authenticated?
  • user - user object that contains all user attributes (email, name, etc.)
  • me - updates the managed session user details and returns it
  • logout - logs the user out by revoking the active session and clearing it from the session manager storage
MainActivity.kt
@Composable
fun StartFlow(context: Context,
              modifier: Modifier = Modifier
) {
    // we create a DescopeSession object that represents an authenticated user session
    fun getUser(): DescopeUser? {
        val session = Descope.sessionManager.session
        if (session !== null) {
            return session.user;
        }
        return null
    }
    fun getUserEmail(): String? {
        val user = getUser();
        if (user !== null) {
            return user.email;
        }
        return null
    }
 
	// ...
}

At this point, you're done with the frontend. If you'd like more detail into frontend Session Management, check out our SDK. If you would like to also handle Session Validation in your backend, keep on reading!

Continue with Backend SDK

If you would like to also handle Session Management in your backend, keep on reading by selecting your backend technology below:


Checkpoint

Your application is now integrated with Descope. Please test with sign-up or sign-in use case.

Need help?

Customize

Now that you have the end-to-end application working, you can choose to configure and personalize many different areas of Descope, including your brand, style, custom user authentication journeys, etc. We recommend starting with customizing your user-facing screens, such as signup and login.

Was this helpful?

On this page