Medartus
Medartus

Reputation: 35

Spotify Api Auth unsupported_grant_type

I'm working on integrating spotify and I'm making my own api. I can't understand why my request is not working. It works fine in python but not when I use express. I get this response body :

{"error":"unsupported_grant_type","error_description":"grant_type must be client_credentials, authorization_code or refresh_token"}

Express :

var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var fetch = require('node-fetch');

var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }))

app.listen(80);

app.post('/v1/spotify/api/token', function(req, res) {

    let body = req.body
    let redirect_uri = body.redirect_uri
    let code = body.code

    let data = {
        grant_type:'authorization_code',
        redirect_uri:redirect_uri,
        code:code
    }

    fetch('https://accounts.spotify.com/api/token', {
        method: 'POST',
        headers: {
            'Authorization':'Basic *client_id:client_secret*',
            'Content-Type':'application/x-www-form-urlencoded'
        },
        body: JSON.stringify(data)
    }).then(r =>  r.json().then(data => res.send(data)))
});

Python:

r = requests.post("https://accounts.spotify.com/api/token",
data={
    "grant_type":"authorization_code",
    "redirect_uri":*redirect_uri*,
    "code":*code*
},
headers = {
    "Authorization": "Basic *client_id:client_secret*",
    'Content-Type':'application/x-www-form-urlencoded'}
)

Upvotes: 0

Views: 1445

Answers (2)

dmc85
dmc85

Reputation: 350

I had to put the client_id and client_secret in the body and not in Authorization header.

try {
    const body = {
      grant_type: "client_credentials",
      client_id: <YOUR_ID>,
      client_secret: <YOUR_SECRET>,
    };

    const response = await fetch("https://accounts.spotify.com/api/token", {
      method: "POST",
      headers: {
        "Content-type": "application/x-www-form-urlencoded",
      },
      body: new URLSearchParams(body),
    });
    console.log({ response });
  } catch (err) {
    console.log({ err });
  }

Upvotes: 0

Tanaike
Tanaike

Reputation: 201613

In your script of Node.js, data is sent as a string value. So how about this modification?

Modified script

Please modify the object of data as follows and try again.

// Below script was added.
const {URLSearchParams} = require('url');
const data = new URLSearchParams();
data.append("grant_type", "authorization_code");
data.append("redirect_uri", redirect_uri);
data.append("code", code);

fetch('https://accounts.spotify.com/api/token', {
    method: 'POST',
    headers: {
        'Authorization':'Basic *client_id:client_secret*',
        'Content-Type':'application/x-www-form-urlencoded'
    },
    body: data // Modified
}).then(r =>  r.json().then(data => res.send(data)))

Reference:

If this didn't work, I apologize.

Upvotes: 2

Related Questions