Kotlin & Django Quickstart

This is a quickstart guide to help you integrate Descope with your Kotlin & Django 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.descope.Descope

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
// Application on create
override fun onCreate() {
    Descope.setup(this, projectId = "__ProjectID__")
 
    // Optionally, you can configure your SDK to your needs
    Descope.setup(this, projectId = "__ProjectID__") {
        // 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()
        }
    }
}

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).

Run your Flow

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

MainActivity.kt
descopeFlowView.listener = object : DescopeFlowView.Listener {
    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): DescopeFlowView.NavigationStrategy {
        // manage navigation event by deciding whether to open the URI
        // in a custom tab (default behavior), inline, or do nothing.
    }
}
 
val descopeFlow = DescopeFlow(Uri.parse("<URL_FOR_FLOW_IN_SETUP_#1>"))
// 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)

Note

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

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!

Install Backend SDK

Install the SDK with the following command:

Terminal
pip install django-descope

Import and Setup Backend SDK

You'll need install and setup all of the packages from the SDK. This is done by ensuring django_descope is under INSTALLED_APPS in settings.py.

If you're using a CNAME with your Descope project, make sure to export the Base URL (e.g. export DESCOPE_BASE_URI="https://api.descope.com") when initializing descope_client.

settings.py
INSTALLED_APPS = [
  ...
  'django_descope',
]
DESCOPE_PROJECT_ID=os.getenv("DESCOPE_PROJECT_ID")

Add Descope Middleware

Ensure Descope Middleware is after the AuthenticationMiddleware and SessionMiddleware.

settings.py
MIDDLEWARE = [
  ...
  'django.contrib.sessions.middleware.SessionMiddleware',
  'django.contrib.auth.middleware.AuthenticationMiddleware',
  ...
  'django_descope.middleware.DescopeMiddleware',
]

Configure URLconf

You will then need to include the Descope URLconf in your project urls.py like this.

urls.py
path('auth/', include('django_descope.urls')),

Configure URLconf

The session validation is handled in the Django SDK, through the middleware.

settings.py
INSTALLED_APPS = [
  ...
  'django_descope',
]
MIDDLEWARE = [
  ...
  'django.contrib.sessions.middleware.SessionMiddleware',
  'django.contrib.auth.middleware.AuthenticationMiddleware',
  ...
  'django_descope.middleware.DescopeMiddleware',
]
DESCOPE_PROJECT_ID=os.getenv("DESCOPE_PROJECT_ID")

Congratulations

Now that you've got the authentication down, go focus on building out the rest of your app!

Here is a sample application using the Django SDK.


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