Tutorial: Sign in user automatically after sign-up in an Android app

This tutorial demonstrates how to sign in user automatically after sign-up in an Android app by using native authentication.

In this tutorial, you learn how to:

  • Sign in after sign-up.
  • Handle errors.

Prerequisites

Sign in after sign-up

After a successful sign-up flow, you can automatically sign in your users without initiating a fresh sign-in flow.

The SignUpResult.Complete returns SignInContinuationState object. The SignInContinuationState object provides access to signIn() method.

To sign up a user with email and password, then automatically sign them in, use the following code snippet:

CoroutineScope(Dispatchers.Main).launch { 
    val signUpActionResult = authClient.signUp( 
        username = emailAddress, 
        password = password 
    ) 
    if (SignUpActionResult is SignUpResult.CodeRequired) { 
        val nextState = signUpActionResult.nextState 
        val submitCodeActionResult = nextState.submitCode( 
            code = code 
        ) 
        if (submitCodeActionResult is SignUpResult.Complete) { 
            // Handle sign up success 
            val signInContinuationState = actionResult.nextState 
            val signInActionResult = signInContinuationState.signIn() 
            if (signInActionResult is SignInResult.Complete) { 
                // Handle sign in success
                val accountState = signInActionResult.resultValue
                val accessTokenResult = accountState.getAccessToken()
                if (accessTokenResult is GetAccessTokenResult.Complete) {
                    val accessToken = accessTokenResult.resultValue.accessToken
                    val idToken = accountState.getIdToken()
                }
            } 
        } 
    } 
}

To retrieve ID token claims after sign-in, use the steps in Read ID token claims.

Handle sign-in errors

The SignInContinuationState.signIn() method returns SignInResult.Complete after a successful sign-in. It can also return an error.

To handle errors in SignInContinuationState.signIn(), use the following code snippet:

val signInContinuationState = actionResult.nextState 
val signInActionResult = signInContinuationState.signIn() 

when (signInActionResult) {
    is SignInResult.Complete -> {
        // Handle sign in success
         displayAccount(accountState = actionResult.resultValue)
    }
    is SignInContinuationError -> {
        // Handle unexpected error
    }
    else -> {
        // Handle unexpected error
    }
}

private fun displayAccount(accountState: AccountState) {
    CoroutineScope(Dispatchers.Main).launch {
        val accessTokenResult = accountState.getAccessToken()
        if (accessTokenResult is GetAccessTokenResult.Complete) {
            val accessToken = accessTokenResult.resultValue.accessToken
            val idToken = accountState.getIdToken()
        }
    }
}

Next steps