Search code examples
httpaccess-tokenspotify

Invalid Access Token: Display Spotify Profile in Web App Tutorial


I'm currently following this tutorial on the Spotify website: https://developer.spotify.com/documentation/web-api/howtos/web-app-profile

The code is simply supposed to redirect you to the Spotify login page where you input your credentials, agree to give your info to my app (accept terms), and then your User ID, email, spotify URI, profile link, and profile image is displayed on the page.

On the getAccessToken function, I'm getting a POST 400 error. On the fetchProfile function, I'm getting a GET 401 error. The console also displays the message:

"Invalid Access Token."

Here is my code for getAccessToken:

export async function getAccessToken(clientId, code) {
    const verifier = localStorage.getItem("verifier");

    const params = new URLSearchParams();
    params.append("client_id", clientId);
    params.append("grant_type", "authorization_code");
    params.append("code", code);
    params.append("redirect_uri", "http://localhost:5173/callback");
    params.append("code_verifier", verifier);

    const result = await fetch("https://accounts.spotify.com/api/token", {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: params
    });

    const { access_token } = await result.json();
    return access_token;
}

Here is my code for fetchProfile:

async function fetchProfile(token){
    const result = await fetch("https://api.spotify.com/v1/me", {
        method: "GET", headers: { Authorization: `Bearer ${token}` }
    });

    return await result.json();
}

All of the ports are correct and I have the correct URI in my Development Dashboard. I've tried adding a CORS mode in the result variable, I cleared my cache, tried another port, etc. I'm new to this and at a complete loss, so if anyone has any solutions that would be greatly appreciated.


Solution

  • Authorization Code Flow in Spotify needs a server feature on the application side.

    It can get code value from Spotify server, then request a token with code.

    In the code flow diagram, explain detail here

    enter image description here

    This code will work

    Save as get-token.js

    const express = require("express")
    const axios = require('axios')
    const cors = require("cors");
    
    const app = express()
    app.use(cors())
    
    CLIENT_ID = "<your client id>"
    CLIENT_SECRET = "<your client secret>"
    PORT = 5173 // it is located in Spotify dashboard's Redirect URIs, my port is 3000
    REDIRECT_URI = `http://localhost:${PORT}/callback` // my case is 'http://localhost:3000/callback'
    SCOPE = [
        "user-read-email",
        "playlist-read-collaborative"
    ]
    
    app.get("/login", (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);
    })
    
    app.get("/callback", 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 => {
                return response.send(JSON.stringify(resp1.data));
            });
    
    })
    
    app.listen(PORT, () => {
        console.log(`Listening on :${PORT}`)
    })
    

    Scopes need to add depends on your API call. Detail information in here.

    Steps

    #1 Install dependencies

    npm install express axios cors
    

    #2 Run Application

    node get-token.js
    

    #3 Open Browser and access this URL

    http://localhost:5173/login
    

    #4 Login with your Spotify credential.

    This login screen automatically shows to you.

    enter image description here

    Result

    In my case port is 3000

    enter image description here