Authorization Beta
In this tutorial, we explain how to use Spotify's Android auth-lib
. The
Android auth-lib
is a small library included in the Android Spotify SDK,
which authenticates the user and allows apps to get an access token or
authorization code through the Spotify client. The access token can then be
used with Spotify's API.
The auth-lib
is independent of the app-remote
library, which is also
included in the Android Spotify SDK.
Library installation
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 a repositories block. Your updated Gradle file should look something like
this:
_11repositories {_11 mavenCentral()_11}_11_11dependencies {_11 implementation 'com.spotify.android:auth:1.2.5' // Maven dependency_11_11 // All other dependencies for your app should also be here:_11 implementation 'androidx.browser:browser:1.0.0'_11 implementation "androidx.appcompat:appcompat:$appCompatVersion"_11}
Authorization methods
There are two basic ways you can authorize your application to get access to the data served by Spotify APIs:
Using the Spotify client to authenticate the user
This is the preferred and recommended method of authentication because users don't need to enter their credentials.
-
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 nativeWebView
. 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 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:
_11// Request code will be used to verify if result comes from the login activity. Can be set to any integer._11private static final int REQUEST_CODE = 1337;_11private static final String REDIRECT_URI = "yourcustomprotocol://callback";_11_11AuthorizationRequest.Builder builder =_11 new AuthorizationRequest.Builder(CLIENT_ID, AuthorizationResponse.Type.TOKEN, REDIRECT_URI);_11_11builder.setScopes(new String[]{"streaming"});_11AuthorizationRequest request = builder.build();_11_11AuthorizationClient.openLoginActivity(this, REQUEST_CODE, request);
To receive the authorization result, your activity needs to override the onActivityResult
callback:
_24protected void onActivityResult(int requestCode, int resultCode, Intent intent) {_24 super.onActivityResult(requestCode, resultCode, intent);_24_24 // Check if result comes from the correct activity_24 if (requestCode == REQUEST_CODE) {_24 AuthorizationResponse response = AuthorizationClient.getResponse(resultCode, intent);_24_24 switch (response.getType()) {_24 // Response was successful and contains auth token_24 case TOKEN:_24 // Handle successful response_24 break;_24_24 // Auth flow returned an error_24 case ERROR:_24 // Handle error response_24 break;_24_24 // Most likely auth flow was cancelled_24 default:_24 // Handle other cases_24 }_24 }_24}
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
Only if the first way is not possible.
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.
Logging in
To log in using the web browser, open it from one of your activities:
_10private static final String REDIRECT_URI = "yourcustomprotocol://callback";_10_10AuthorizationRequest.Builder builder =_10 new AuthorizationRequest.Builder(CLIENT_ID, AuthorizationResponse.Type.TOKEN, REDIRECT_URI);_10_10builder.setScopes(new String[]{"streaming"});_10AuthorizationRequest request = builder.build();_10_10AuthorizationClient.openLoginInBrowser(this, request);
The activity that will receive and process the result must be configured in the AndroidManifest.xml
:
_23<activity_23 android:name=".MySpotifyAuthorizationActivity"_23 android:label="@string/app_name"_23 android:launchMode="singleInstance" >_23_23 // An intent filter that will receive the response_23 // from the authentication service_23 <intent-filter>_23 <action android:name="android.intent.action.VIEW"/>_23_23 <category android:name="android.intent.category.DEFAULT"/>_23 <category android:name="android.intent.category.BROWSABLE"/>_23_23 // this needs to match the scheme and host of the redirect URI as defined in My applications page_23 <data_23 android:host="callback"_23 android:scheme="yourcustomprotocol"/>_23 </intent-filter>_23_23 <intent-filter>_23 // Other intent filters this activity requires_23 </intent-filter>_23</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
:
_22protected void onNewIntent(Intent intent) {_22 super.onNewIntent(intent);_22_22 Uri uri = intent.getData();_22 if (uri != null) {_22 AuthorizationResponse response = AuthorizationResponse.fromUri(uri);_22_22 switch (response.getType()) {_22 // Response was successful and contains auth token_22 case TOKEN:_22 // Handle successful response_22 break;_22_22 // Auth flow returned an error_22 case ERROR:_22 // Handle error response_22 break;_22_22 // Most likely auth flow was cancelled_22 default:_22 // Handle other cases_22 }
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 mode.
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:
_10private static final String REDIRECT_URI = "yourcustomprotocol://callback";_10_10AuthorizationRequest.Builder builder =_10 new AuthorizationRequest.Builder(CLIENT_ID, AuthorizationResponse.Type.TOKEN, REDIRECT_URI);_10_10builder.setScopes(new String[]{"streaming"});_10builder.setShowDialog(true);_10AuthorizationRequest request = builder.build();_10_10AuthorizationClient.openLoginInBrowser(this, request);