Android SDK Authentication Guide Beta
In this guide, we explain how to use Spotify’s Android auth-lib. The Android auth-lib is a small library included in the Android Spotify SDK. The auth-lib is independent from the app-remote library, which is also included in the Android Spotify SDK. The auth-lib allows apps to get an access token through the Spotify client. The access token can be then used with Spotify’s API.
There are two basic ways you can authorize your application to get access to the data served by Spotify APIs:
- 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, the auth-lib connects to the Spotify client and uses the current session. If Spotify is not installed, this method will fall back to use Android
WebView
class which allows you to display a web page as part of your activity layout. In this case, authentication and authorization takes place in theWebView
without leaving the application. This method is preferred because it allows the user to authorize your app in a more seamless way, since they don’t need to enter their credentials. - 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. This method does not involve the auth-lib.
Topics
- Adding the Library to the Project
- Single Sign-On with Spotify Client and a WebView Fallback
- Login Through a Web Browser - Without auth-lib
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 {
implementation 'com.spotify.android:auth:1.1.0' // Maven dependency
// All other dependencies for your app should also be here:
implementation 'androidx.browser:browser:1.0.0'
implementation "androidx.appcompat:appcompat:$appCompatVersion"
}
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:
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);