Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replaced the deprecated Request library with recommended Axios library and rewrite by using ES6 #45

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
# Spotify Accounts Authentication Examples
# Spotify Accounts Authentication Examples (Updated)

## Note

**As of Feb 11th 2020, request is fully deprecated. No new changes are expected land. In fact, none have landed for some time.**

In these examples, I replaced the request by using axios and I also rewrite the code to ES6.

This project contains basic demos showing the different OAuth 2.0 flows for [authenticating against the Spotify Web API](https://developer.spotify.com/web-api/authorization-guide/).

Expand Down
193 changes: 94 additions & 99 deletions authorization_code/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,141 +7,136 @@
* https://developer.spotify.com/web-api/authorization-guide/#authorization_code_flow
*/

var express = require('express'); // Express web server framework
var request = require('request'); // "Request" library
var cors = require('cors');
var querystring = require('querystring');
var cookieParser = require('cookie-parser');
const express = require("express"); // Express web server framework
const axios = require("axios");
const cors = require("cors");
const querystring = require("querystring");
const cookieParser = require("cookie-parser");

var client_id = 'CLIENT_ID'; // Your client id
var client_secret = 'CLIENT_SECRET'; // Your secret
var redirect_uri = 'REDIRECT_URI'; // Your redirect uri
const client_id = "CLIENT_ID"; // Your client id
const client_secret = "CLIENT_SECRET"; // Your secret
const redirect_uri = "REDIRECT_URI"; // Your redirect uri

/**
* Generates a random string containing numbers and letters
* @param {number} length The length of the string
* @return {string} The generated string
*/
var generateRandomString = function(length) {
var text = '';
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const generateRandomString = function(length) {
let text = "";
let possible =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

for (var i = 0; i < length; i++) {
for (let i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
};

var stateKey = 'spotify_auth_state';
const stateKey = "spotify_auth_state";

var app = express();
const app = express();

app.use(express.static(__dirname + '/public'))
.use(cors())
.use(cookieParser());
app
.use(express.static(__dirname + "/public"))
.use(cors())
.use(cookieParser());

app.get('/login', function(req, res) {

var state = generateRandomString(16);
app.get("/login", function(req, res) {
let state = generateRandomString(16);
res.cookie(stateKey, state);

// your application requests authorization
var scope = 'user-read-private user-read-email';
res.redirect('https://accounts.spotify.com/authorize?' +
querystring.stringify({
response_type: 'code',
client_id: client_id,
scope: scope,
redirect_uri: redirect_uri,
state: state
}));
let scope = "user-read-private user-read-email";
res.redirect(
"https://accounts.spotify.com/authorize?" +
querystring.stringify({
response_type: "code",
client_id: client_id,
scope: scope,
redirect_uri: redirect_uri,
state: state
})
);
});

app.get('/callback', function(req, res) {

app.get("/callback", function(req, res) {
// your application requests refresh and access tokens
// after checking the state parameter

var code = req.query.code || null;
var state = req.query.state || null;
var storedState = req.cookies ? req.cookies[stateKey] : null;
let code = req.query.code || null;
let state = req.query.state || null;
let storedState = req.cookies ? req.cookies[stateKey] : null;

if (state === null || state !== storedState) {
res.redirect('/#' +
querystring.stringify({
error: 'state_mismatch'
}));
res.redirect("/#" + querystring.stringify({ error: "state_mismatch" }));
} else {
res.clearCookie(stateKey);
var authOptions = {
url: 'https://accounts.spotify.com/api/token',
form: {
code: code,
redirect_uri: redirect_uri,
grant_type: 'authorization_code'
},
headers: {
'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64'))
},
json: true
// your application requests authorization
const params = {
client_id,
client_secret,
redirect_uri,
code,
grant_type: "authorization_code"
};

request.post(authOptions, function(error, response, body) {
if (!error && response.statusCode === 200) {

var access_token = body.access_token,
refresh_token = body.refresh_token;

var options = {
url: 'https://api.spotify.com/v1/me',
headers: { 'Authorization': 'Bearer ' + access_token },
json: true
};

// use the access token to access the Spotify Web API
request.get(options, function(error, response, body) {
console.log(body);
});

// we can also pass the token to the browser to make requests from there
res.redirect('/#' +
querystring.stringify({
access_token: access_token,
refresh_token: refresh_token
}));
} else {
res.redirect('/#' +
querystring.stringify({
error: 'invalid_token'
}));
axios({
method: "post",
url: "https://accounts.spotify.com/api/token",
params,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
});
})
.then(response => {
const access_token = response.data.access_token;
const refresh_token = response.data.refresh_token;
axios({
method: "get",
url: "https://api.spotify.com/v1/me",
headers: { Authorization: "Bearer " + access_token }
})
.then(() => {
res.redirect(
"/#" + querystring.stringify({ access_token, refresh_token })
);
})
.catch(e => {
res.redirect(
"/#" + querystring.stringify({ error: e.response.data })
);
});
})
.catch(e => console.error(e.response.data));
}
});

app.get('/refresh_token', function(req, res) {

app.get("/refresh_token", function(req, res) {
// requesting access token from refresh token
var refresh_token = req.query.refresh_token;
var authOptions = {
url: 'https://accounts.spotify.com/api/token',
headers: { 'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64')) },
form: {
grant_type: 'refresh_token',
refresh_token: refresh_token
},
json: true
const refresh_token = req.query.refresh_token;
const params = {
client_id,
client_secret,
grant_type: "refresh_token",
refresh_token: refresh_token
};

request.post(authOptions, function(error, response, body) {
if (!error && response.statusCode === 200) {
var access_token = body.access_token;
axios({
method: "post",
url: "https://accounts.spotify.com/api/token",
params,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
})
.then(response => {
access_token = response.data.access_token;
res.send({
'access_token': access_token
access_token: access_token
});
}
});
})
.catch(e => {
console.error(e.response.data);
});
});

console.log('Listening on 8888');
console.log("Listening on 8888");
app.listen(8888);
49 changes: 20 additions & 29 deletions client_credentials/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,38 +6,29 @@
* For more information, read
* https://developer.spotify.com/web-api/authorization-guide/#client_credentials_flow
*/
const axios = require('axios');

var request = require('request'); // "Request" library
const client_id = 'CLIENT_ID'; // Your client id
const client_secret = 'CLIENT_SECRET'; // Your secret

var client_id = 'CLIENT_ID'; // Your client id
var client_secret = 'CLIENT_SECRET'; // Your secret
const params = {
client_id,
client_secret,
grant_type: "client_credentials"
};

// your application requests authorization
var authOptions = {
axios({
method: "post",
url: 'https://accounts.spotify.com/api/token',
params,
headers: {
'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64'))
},
form: {
grant_type: 'client_credentials'
},
json: true
};

request.post(authOptions, function(error, response, body) {
if (!error && response.statusCode === 200) {

// use the access token to access the Spotify Web API
var token = body.access_token;
var options = {
url: 'https://api.spotify.com/v1/users/jmperezperez',
headers: {
'Authorization': 'Bearer ' + token
},
json: true
};
request.get(options, function(error, response, body) {
console.log(body);
});
"Content-Type": "application/x-www-form-urlencoded"
}
});
}).then(response=>{
const token = response.data.access_token
axios({
method:"get",
url: 'https://api.spotify.com/v1/users/jmperezperez',
headers: {'Authorization': 'Bearer ' + token},
}).then(response=>console.log(response.data)).catch(err=>console.error(err))
}).catch(error=>console.error(error))
Loading