0

I am playing around with Spotify's API and I am trying to get the authorization from the user using res.redirect, but the authorization dialogue is not showing up. Here is the code. Additional info the redirect URL is localhost:3000, and the js script is connect to a static folder which has one html file .

const Joi = require('joi');
const querystring = require('querystring');
const express = require('express');
const cors = require('cors');
const request = require('request');
const cookieParser = require('cookie-parser');
const app = express();
app.use(express.json()); //middleware
app.use(express.static(__dirname + '/public'))
  .use(cors())
  .use(cookieParser());

app.get('/user', (req, res) => {

  const client_id = 'b*****************';
  const redirect_uri = 'http://localhost:3000/';
  const scope = 'user-read-private user-read-email';
  res.redirect('https://accounts.spotify.com/authorize?' + querystring.stringify({
    response_type: 'code',
    client_id: client_id,
    redirect_uri: redirect_uri

  }));


});

app.listen(3000);
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

0

if you’re implementing authorization in a mobile app, single page web app, or any other type of application where the client secret can’t be safely stored. Authorization Code with PKCE Flow in here

I will demo a more simple version Authorization Code Flow but the concept is the same.

Authorization Code Flow in here

enter image description here

Demo code save as demo.js

const axios = require('axios')
const express = require('express')
const cors = require('cors')
const app = express()
app.use(cors())

// for raw JSON of Body
app.use(express.json());

const REDIRECT_URI='http://localhost:3000' // mine is http://localhost:3000/callback
const CLIENT_ID='<your client ID>'
const CLIENT_SECRET='<your client secret>'
const SCOPE=['playlist-read-private']
const PORT = 3000
const PLATLIST_ID='<your playlist ID>'

// User login URL
app.get("/user", (request, response) => {
    const redirect_url = `https://accounts.spotify.com/authorize?response_type=code&client_id=${CLIENT_ID}&scope=${SCOPE}&state=123456&redirect_uri=${REDIRECT_URI}&prompt=consent`
    response.redirect(redirect_url)
})

// callback URL
app.get("/", async (request, response) => {
    const code = request.query["code"]
    await axios.post(
        url = 'https://accounts.spotify.com/api/token',
        data = new URLSearchParams({
            'grant_type': 'authorization_code',
            'redirect_uri': REDIRECT_URI,
            'code': code
        }),
        config = {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            params: {
                'grant_type': 'client_credentials'
            },
            auth: {
                username: CLIENT_ID,
                password: CLIENT_SECRET
            }
        })
        .then(resp1 => {
            axios.get(
                url = `https://api.spotify.com/v1/playlists/${PLATLIST_ID}`,
                config = {
                    headers: {
                        'Accept-Encoding': 'application/json',
                        Authorization: `Bearer ${resp1.data.access_token}`
                    }
                }
            ).then(resp2 => {
                return response.send(JSON.stringify(resp2.data));
            })
        });

})
// use your <your redirect URL>'s port
app.listen(PORT, () => { console.log(`Listening on : http://localhost:${PORT}`) })

Install dependencies

npm install axios express cors

Run the server

node demo.js

Login to get a token by Browser

http://localhost:3000/user

Login Dialog will show

enter image description here

Result from express server

enter image description here

Scopes

Each API need to match scope, Example,

API Scope URL
Get Playlist playlist-read-private https://developer.spotify.com/documentation/web-api/reference/get-playlists-tracks
Create Playlist playlist-modify-public, playlist-modify-private https://developer.spotify.com/documentation/web-api/reference/create-playlist
https://developer.spotify.com/documentation/web-api/concepts/scopes
Bench Vue
  • 5,257
  • 2
  • 10
  • 14
  • I am only getting the login dialogue only once after that it's not showing again, what should I do? – anesunyakonda Jul 17 '23 at 09:11
  • Change the redirect URI from "http://localhost:3000" to "http://localhost:3000/callback" at Dash board in [here](https://stackoverflow.com/questions/76559444/issue-im-trying-to-pause-spotify-playing-using-a-python-script/76560961#76560961) and change code from `app.get("/", async (request, response)` to ``app.get("/callback", async (request, response)`` in demo.js, Then try again. – Bench Vue Jul 17 '23 at 09:27