Android SDK Authentication and Authorization 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 of the app-remote library, which is also included in the Android Spotify SDK. The auth-lib authenticates the user and allows apps to get an access token or authorization code 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
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. Check Maven Central Repository to make sure you’re using the latest library version in your project.
To be able to get the library dependency, you should also add mavenCentral()
into repositories block. Your updated Gradle file should look something like this:
repositories {
mavenCentral()
}
dependencies {
implementation 'com.spotify.android:auth:1.2.5' // 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 auth-lib will try to fetch the authorization code/access token using the Spotify Android client.
If Spotify is installed on the device, the auth-lib will connect to the Spotify client and fetch the authorization code/access token for the current user. Since the user is already logged into Spotify, they don’t need to type in their username and password. If the 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 auth-lib 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:
// 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";
AuthorizationRequest.Builder builder =
new AuthorizationRequest.Builder(CLIENT_ID, AuthorizationResponse.Type.TOKEN, REDIRECT_URI);
builder.setScopes(new String[]{"streaming"});
AuthorizationRequest request = builder.build();
AuthorizationClient.openLoginActivity(this, REQUEST_CODE, request);
To receive the authorization result, your 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) {
AuthorizationResponse response = AuthorizationClient.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 AuthorizationClient#clearCookies
method. Both Spotify and Facebook tokens will be removed.
Login Through a Web Browser
In this flow the auth-lib creates an intent that opens the web browser that performs authentication and authorization. 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:
private static final String REDIRECT_URI = "yourcustomprotocol://callback";
AuthorizationRequest.Builder builder =
new AuthorizationRequest.Builder(CLIENT_ID, AuthorizationResponse.Type.TOKEN, REDIRECT_URI);
builder.setScopes(new String[]{"streaming"});
AuthorizationRequest request = builder.build();
AuthorizationClient.openLoginInBrowser(this, request);
The activity that will receive and process the result must be configured in the AndroidManifest.xml
:
<activity
android:name=".MySpotifyAuthorizationActivity"
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 (MySpotifyAuthorizationActivity
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) {
AuthorizationResponse response = AuthorizationResponse.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 the authorization 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 authorization 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:
private static final String REDIRECT_URI = "yourcustomprotocol://callback";
AuthorizationRequest.Builder builder =
new AuthorizationRequest.Builder(CLIENT_ID, AuthorizationResponse.Type.TOKEN, REDIRECT_URI);
builder.setScopes(new String[]{"streaming"});
builder.setShowDialog(true);
AuthorizationRequest request = builder.build();
AuthorizationClient.openLoginInBrowser(this, request);