Unsupported grant type error when requesting access_token on Spotify API with Meteor HTTP
Asked Answered
R

2

8

I've been unable to solve a problem while requesting an access_token on Spotify API with Meteor HTTP. Indeed, when I make a POST call to the Spotify https://accounts.spotify.com/api/token. I get the following response :

{"statusCode":400,"content":"{\"error\":\"unsupported_grant_type\",\"error_description\":\"grant_type must be client_credentials, authorization_code or refresh_token\"}"

I think this may have something to do with the Content-Type header and the encoding of the BODY parameter but I haven't been able to solve this issue. I tried to use both data and params and none of these worked.

Here is my code :

HTTP.post("https://accounts.spotify.com/api/token", {
      data: {
        grant_type : "authorization_code",
        code : authCode,
        redirect_uri : Router.routes['redirect_spotify'].url()
      },
      headers: {
        'Authorization' : "Basic " + CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse("xxxx:yyyyy")),
        'Content-Type':'application/x-www-form-urlencoded'
      }
    }, function(error, result) {
      console.log("POST made with data : %j", result);
      if (error){
        Registrations.remove({userId : this.userId });
        return;
      }
      Registrations.update({
        userId : this.userId },
      {$set : {
        state: "Done",
        accessToken: result.access_token,
        //TODO expires
        refreshToken: result.refresh_token
        }},
      { upsert : true}
    );
    });

Thank you all in advance :) Love Meteor

Respectability answered 26/1, 2015 at 21:43 Comment(2)
I'm assuming you replaced "authorization_code" with your authorization code, right?Trove
the authorization_code is a string defining the scheme of authorization. The authorization code goes in the codeRespectability
P
18

You need to use params instead of data. Thus, your code would be:

HTTP.post("https://accounts.spotify.com/api/token", {
  params: {
    grant_type : "authorization_code",
    code : authCode,
    redirect_uri : Router.routes['redirect_spotify'].url()
  },
  headers: {
    'Authorization' : "Basic " + CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse("xxxx:yyyyy")),
    'Content-Type':'application/x-www-form-urlencoded'
  }
}, function(error, result) {
   ...
});
Platinumblond answered 27/1, 2015 at 10:6 Comment(1)
This helped me figure out to put use query instead of body for Swift Vapor HTTP post. Thank youLeavy
K
1

Sending data in the format query params in the request body also works when the method is POST.

For example: Sending the data values, name = 'Tommy' and age = 26 in the request body as

name=Tommy&age=26
Kimes answered 9/3, 2020 at 4:24 Comment(1)
this fixed my problem trying to send the authorization information overCray

© 2022 - 2024 — McMap. All rights reserved.