On 11 September 2018, we made updates to our iOS and Android SDKs. These new SDKs work for both Spotify Free and Spotify Premium users, offer built-in offline support, and more. Read more about the updates on our blog.
Want to access the 2014 Android streaming SDK? It is available on GitHub by clicking here.

In this guide we describe two flows for authenticating your application’s user from within the Spotify Android SDK.

Topics

There are two basic ways you can authenticate your application’s user and pass the scopes needed to get authorization to access user data:

  • The preferred and highly recommended way: Use the Spotify client to authenticate the user (with a fallback to login through a WebView). If Spotify is installed on the device, SDK connects to the Spotify client and uses current session. If Spotify is not installed, this method will fall back to using Android WebView class which allows you to display a web page as part of your activity layout. Authentication and authorization takes place in the WebView without leaving the application.
  • Only if the first way is not possible: Login through a web browser. This method opens the Spotify Accounts page in a separate, external browser window, completes the authentication process, and then redirects back to your application.

Adding the Library to the Project

To authenticate user with Spotify, you need to use the authentication library provided in the SDK.

Download the Spotify Android auth library zip file from GitHub and unzip it.

Copy the spotify-auth-version.aar file into the /app/libs directory in your project’s root directory.

In Android Studio, edit the build.gradle file in the app directory (it can also be labelled as Module: app) and make sure it contains the dependency on the library:

repositories {
    mavenCentral()
    flatDir {
        dirs 'libs'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.spotify.sdk:spotify-auth:<version>@aar'

    // All other dependencies for your app should also be here:
    compile 'com.android.support:appcompat-v7:21.0.3'
}

Single Sign-On with Spotify Client and a WebView Fallback

In this flow, the Android SDK will try to fetch the authorization code/access token using the Spotify Android client.

Note: to be able to use Single Sign-On you need to register your application’s fingerprint. Please see Registering Application Fingerprint section of the tutorial.

If Spotify is installed on the device, the SDK will connect to the Spotify client and fetch the authorization code/access token for current user. Since the user is already logged into Spotify, they don’t need to type in their username and password. If the SDK application requests scopes that have not been approved before, the user will see a list of scopes and will need to accept them.

If Spotify is not installed on the device, the SDK will fallback to the WebView based authorization and open the Spotify Accounts login page at https://accounts.spotify.com in a native WebView. User will have to enter their username and password to login to Spotify and accept the supplied scopes.

In both cases the result of the authorization flow will be returned in the onActivityResult method of the activity that initiated it.

This flow is entirely completed within the application; there is no need to open a web browser.

Logging In

To login using this flow, open the LoginActivity from one of your activities using the provided helpers:

// Request code will be used to verify if result comes from the login activity. Can be set to any integer.
private static final int REQUEST_CODE = 1337;
private static final String REDIRECT_URI = "yourcustomprotocol://callback";

AuthenticationRequest.Builder builder =
        new AuthenticationRequest.Builder(CLIENT_ID, AuthenticationResponse.Type.TOKEN, REDIRECT_URI);

builder.setScopes(new String[]{"streaming"});
AuthenticationRequest request = builder.build();

AuthenticationClient.openLoginActivity(this, REQUEST_CODE, request);

For login flow to work, LoginActivity needs to be added to AndroidManifest.xml:

<activity
    android:name="com.spotify.sdk.android.authentication.LoginActivity"
    android:theme="@android:style/Theme.Translucent.NoTitleBar" />

To receive the authentication result, activity needs to override the onActivityResult callback:

protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
     super.onActivityResult(requestCode, resultCode, intent);

     // Check if result comes from the correct activity
     if (requestCode == REQUEST_CODE) {
        AuthenticationResponse response = AuthenticationClient.getResponse(resultCode, intent);

        switch (response.getType()) {
            // Response was successful and contains auth token
            case TOKEN:
                // Handle successful response
                break;

            // Auth flow returned an error
            case ERROR:
                // Handle error response
                break;

            // Most likely auth flow was cancelled
            default:
               // Handle other cases
         }
     }
}

Logging Out

By default, the authenticated session is persisted in the WebView, which allows user to log in again without re-typing in their password.

To log out and clear all stored tokens, use the AuthenticationClient#clearCookies method. Both Spotify and Facebook tokens will be removed.

Login Through a Web Browser

In this flow the SDK creates an intent that opens the web browser that performs authorization and authentication. After this process is completed, browser redirects back to the app. This flow takes the user outside the application.

Logging in

To log in using the web browser, open it from one of your activities using the provided helpers:

private static final String REDIRECT_URI = "yourcustomprotocol://callback";

AuthenticationRequest.Builder builder =
        new AuthenticationRequest.Builder(CLIENT_ID, AuthenticationResponse.Type.TOKEN, REDIRECT_URI);

builder.setScopes(new String[]{"streaming"})
AuthenticationRequest request = builder.build();

AuthenticationClient.openLoginInBrowser(this, request);

The activity that will receive and process the result of authentication must be configured in the AndroidManifest.xml:

<activity
      android:name=".MySpotifyAuthenticationActivity"
      android:label="@string/app_name"
      android:launchMode="singleInstance" >

      // An intent filter that will receive the response
      // from the authentication service
      <intent-filter>
          <action android:name="android.intent.action.VIEW"/>

          <category android:name="android.intent.category.DEFAULT"/>
          <category android:name="android.intent.category.BROWSABLE"/>

          // this needs to match the scheme and host of the redirect URI as defined in My applications page
          <data
              android:host="callback"
              android:scheme="yourcustomprotocol"/>
     </intent-filter>

     <intent-filter>
          // Other intent filters this activity requires
      </intent-filter>
</activity>

To process the result, the receiving activity (MySpotifyAuthenticationActivity in this example) needs to override one of its callbacks. With launch mode set to singleInstance or singleTask the callback to use is onNewIntent:

protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);

    Uri uri = intent.getData();
    if (uri != null) {
        AuthenticationResponse response = AuthenticationResponse.fromUri(uri);

        switch (response.getType()) {
            // Response was successful and contains auth token
            case TOKEN:
                // Handle successful response
                break;

            // Auth flow returned an error
            case ERROR:
                // Handle error response
                break;

            // Most likely auth flow was cancelled
            default:
               // Handle other cases
         }

It is also possible to use other launch modes for the activity that processes authentication result. In this case it can be either onNewIntent or onCreate callback that will receive an intent containing the result. See information about launch modes in Android to choose the correct one.

Be aware of the fact that activities launched in standard or singleTop mode can have multiple instances existing at the same time. Make sure you don’t create multiple Player instances in your application.

Logging out from Spotify

To log out user from Spotify in the app, they must be logged out using the same browser they used to log in. To log out, open url https://accounts.spotify.com in the browser. The user that is currently logged in will then be able to log out:

Android log out screen

Another option to log out is to add showDialog parameter to the authentication request. This will force the page that lists the granted scopes and currently logged in user giving them the chance to log out by choosing the “Not you?” link:

AuthenticationRequest.Builder builder =
        new AuthenticationRequest.Builder(CLIENT_ID, AuthenticationResponse.Type.TOKEN, REDIRECT_URI);

builder.setScopes(new String[]{"streaming"})
builder.setShowDialog(true);
AuthenticationRequest request = builder.build();

AuthenticationClient.openLoginInBrowser(this, request);

Android log out screen

Logging out from Facebook

If user has a Facebook account they can use it to log in to Spotify. In this case logging out of Spotify using methods described above does not mean that user is logged out from their Facebook account. As long as the Facebook session in the browser is valid, pressing the “Login with Facebook” button will log the user in automatically.

To switch Facebook users they will first need to manually logout from Facebook in their browser.