Add Login to an Android App with the FusionAuth Kotlin SDK

On this page

The Kotlin SDK adds login and logout to an Android app, with FusionAuth as the authorization serverThe server that authenticates users and issues tokens to applications in OAuth 2.0. FusionAuth is an authorization server.. The SDK runs the OAuth 2.0 Authorization Code grant with PKCEAn extension to OAuth 2.0 that mitigates authorization code interception attacks using dynamic code verifiers and challenges. through AppAuth-Android, then stores and refreshes the tokens for you. The SDK works from Kotlin and Java. To build a complete app step by step, see the Android QuickStart.

Prerequisites#

  • Android 7.0 (API level 24) or later.
  • A FusionAuth ApplicationA software program that your users log in to through FusionAuth. configured as a public clientAn OAuth 2.0 client that can't keep a client secret private, such as a single-page or mobile application. A public client uses PKCE instead of a client secret.. On the OAuth tab of the Application:
    • Set Client Authentication to Not required when using PKCE, because an Android app can't keep a client secret.
    • Add io.fusionauth.app:/oauth2redirect to Authorized redirect URLs. The SDK uses this URL after login and after logout.

Add Login to Your App#

The SDK functions in the following steps are suspend functions. Call the functions from a coroutine, such as lifecycleScope.launch { } in an activity.

  1. Add the SDK to app/build.gradle.kts, and register the redirect URL scheme:

    android {
        defaultConfig {
            manifestPlaceholders["appAuthRedirectScheme"] = "io.fusionauth.app"
        }
    }
    
    dependencies {
        implementation("io.fusionauth:fusionauth-android-sdk:1.2.0")
    }
    

    AppAuth reads appAuthRedirectScheme to send the redirect from FusionAuth back to your app. The scheme must match the scheme of the redirect URL. For newer versions of the SDK, see fusionauth-android-sdk on Maven Central.

  2. Initialize the AuthorizationManager when your app starts. Set fusionAuthUrl to the URL of your FusionAuth instance and clientId to the client Id of your FusionAuth Application. Pass DataStoreStorage to keep the tokens when the app restarts:

    AuthorizationManager.initialize(
        AuthorizationConfiguration(
            fusionAuthUrl = "http://10.0.2.2:9011",
            clientId = "e9fdb985-9173-4e01-9d73-ac2d60d1dc8e",
            allowUnsecureConnection = true
        ),
        DataStoreStorage(this)
    )
    

    10.0.2.2 is the address of your computer from the Android Emulator. allowUnsecureConnection allows the http URL. Remove allowUnsecureConnection when FusionAuth uses https. Without a storage argument, the SDK keeps the tokens in memory, and the user logs in again each time the app starts.

  3. Call authorize to start login. Pass the activity to open after login:

    AuthorizationManager
        .oAuth(this@LoginActivity)
        .authorize(
            Intent(this@LoginActivity, TokenActivity::class.java),
            OAuthAuthorizeOptions(
                cancelIntent = Intent(this@LoginActivity, LoginActivity::class.java)
                    .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            )
        )
    

    authorize opens the FusionAuth login page in a browser. cancelIntent sets the activity to open when the user cancels login.

  4. Call handleRedirect in the activity that opens after login:

    AuthorizationManager
        .oAuth(this@TokenActivity)
        .handleRedirect(intent)
    

    handleRedirect exchanges the authorization code for an access token and a refresh token, and stores the tokens.

  5. Call logout to log the user out. Pass the activity to open after logout:

    AuthorizationManager
        .oAuth(this@TokenActivity)
        .logout(
            Intent(this@TokenActivity, LoginActivity::class.java)
                .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        )
    

    logout ends the FusionAuth session and removes the stored tokens.

  6. Run the app and start login. The FusionAuth login page opens. After you log in, FusionAuth returns you to TokenActivity.

Get the User's Profile#

Call getUserInfo to load the user's UserInfo claims, such as the email address:

val userInfo = AuthorizationManager
    .oAuth(this@TokenActivity)
    .getUserInfo()

Call Your APIs with an Access Token#

Call freshAccessToken before each API call. The SDK returns the stored access token, and refreshes the token first when the token has expired:

val accessToken = AuthorizationManager.freshAccessToken(this@TokenActivity)

Send the token in the Authorization header as Bearer <token>.

Use a Different Redirect URL#

To use a redirect URL with your own scheme, set appAuthRedirectScheme to the scheme. Then pass the URL as redirectUri in OAuthAuthorizeOptions, and as postLogoutRedirectUri in OAuthLogoutOptions. Add the URL to Authorized redirect URLs on the Application.

Read the Configuration from a File#

To keep the configuration out of your code, put a fusionauth_config.json file in the res/raw directory:

{
  "fusionAuthUrl": "http://10.0.2.2:9011",
  "clientId": "e9fdb985-9173-4e01-9d73-ac2d60d1dc8e",
  "allowUnsecureConnection": true
}

Then read the file with fromResources:

AuthorizationManager.initialize(
    AuthorizationConfiguration.fromResources(this, R.raw.fusionauth_config),
    DataStoreStorage(this)
)

For every class and option in the SDK, see the Android SDK reference.