Skip to content

Instantly share code, notes, and snippets.

@rldaulton
Last active February 10, 2021 00:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rldaulton/8b87216715d3cea828b5a9b27e300a3f to your computer and use it in GitHub Desktop.
Save rldaulton/8b87216715d3cea828b5a9b27e300a3f to your computer and use it in GitHub Desktop.
Spotify Authorization Code Flow [Android helper] using Google Cloud Functions
/*
* A Spotify Authorization Code Flow, used specifically for Android.
* I have been trying to do a refresh token in an android client, but I
* notice that when a user logs in using Spotify's SDK, they do not
* receive a refresh_token. I do not want my users to have to log in every
* time they use the app.
*
* After finding this issue:
*
* https://github.com/spotify/android-sdk/issues/259
*
* ...Decided to make my own solution using stateless Google Cloud Functions
* and using: https://github.com/thelinmichael/spotify-web-api-node
*
* It's a bit hacky right now, but it does the job.
*
* -Ryan
* -Red Shepard Software
*
* Oh yea, license MIT. Use this however the hell you want.
*/
var app = require('express')();
var SpotifyWebApi = require('spotify-web-api-node');
var bodyParser = require('body-parser');
/*
* MARK: - Invocation
* Using an HTTP Trigger, hitting your cloud endpoint, just
* include ".../your_code" at the end of the url.
*
* Pass in EITHER your Authorization Code OR a refresh_tok.
*
* This function extracts it, checks if it is a CODE or
* an refresh token, then re-authenticates and sends back
* new refresh & access tokens.
*/
exports.spotifyAuth = app.get("/:code", function auth (req,res){
var code = req.params.code;
var credentials = {
clientId : 'your_client_id',
clientSecret : 'your_client_secret',
redirectUri : 'http//:some_redirect_url'
};
var spotifyApi = new SpotifyWebApi(credentials);
// MARK: - CODE Check
// Spotify authorization code is a 131 char code.
// A refresh_token is a 239 char code.
// Simple check to determine which has been passed in.
if (code.length > 131) {
// Retrieve an access token and a refresh token
spotifyApi.authorizationCodeGrant(code)
.then(function(data) {
// If you need to log these, uncomment:
// console.log('The token expires in ' + data.body['expires_in']);
// console.log('The access token is ' + data.body['access_token']);
// console.log('The refresh token is ' + data.body['refresh_token']);
res.json(data);
}, function(err) {
console.log('Authorization Code Grant Flow ERROR: ', err);
});
} else {
spotifyApi.setRefreshToken(code);
spotifyApi.refreshAccessToken()
.then(function(refdata) {
// returns JSON values:
// "access_token": "NgA6ZcYI...ixn8bUQ",
// "token_type": "Bearer",
// "scope": "[requested_scope]..",
// "expires_in": "somedate"
res.json(refdata);
}, function(err) {
console.log('Could not refresh the token!', err.message);
});
}
});
@rldaulton
Copy link
Author

rldaulton commented Mar 15, 2017

In addition, if you're a beginner and you need package.json contents, here is an example of mine for this function:

{
  "name": "[your_app]-SpotifyAuth",
  "version": "1.0.0",
  "description": "Spotify Authorization Grant Flow for Android",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "[your_name]",
  "license": "MIT",
  "dependencies": {
    "express": "^4.14.0",
    "spotify-web-api-node" : "2.3.6",
    "body-parser": "~1.13.3",
    "async": "^2.0.1",
    "promise": "^7.1.1"
  },
  "engines": {
    "node": "4.1.1"
  }
}

@Ayc0
Copy link

Ayc0 commented Nov 22, 2017

instead of doing res.send(JSON.stringify(...)), you can do res.json(...) (and you don't even need the res.contentType('application/json'))

@HwanChoi
Copy link

I have a question about your post. I am developing Android Spotify Applciation with SDK provided by Official Site.
I have faced problem for Refreshing Auth Token (it is working only for a hour). There are no way to resolve with Android SDK. finally I have found your post!
however I don't have knowledge of web programming!
new SpotifyWebApi What is this? and how can I support your code and need web server to use your code?
Please let me explain It help me support refreshing function for Android app.
Thank you.

@hendrowijaya96
Copy link

how to use this in android?

@rldaulton
Copy link
Author

I have a question about your post. I am developing Android Spotify Applciation with SDK provided by Official Site.
I have faced problem for Refreshing Auth Token (it is working only for a hour). There are no way to resolve with Android SDK. finally I have found your post!
however I don't have knowledge of web programming!
new SpotifyWebApi What is this? and how can I support your code and need web server to use your code?
Please let me explain It help me support refreshing function for Android app.
Thank you.

@HwanChoi sorry for the extremely late response, but for anyone else looking at this post the SpotifyWebApi he is referring to is an npm package that must be installed to use my example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment