0
votes

I'm trying to use Authorization Code flow instead of Implicit Grant which I use currently. Here is documentation of both flows. I'm using spotify API from my Angular 2 application. First three steps go well and I get code from callback call. But when I make post call to https://accounts.spotify.com/api/token I get CORS exception because call returns website which is prohibited by browsers. Return page is same as clicking this link https://accounts.spotify.com/api/token. I try call this api by using curl and here is what I notice. When calling this:

curl -H "Authorization: Basic ZjM...zE=" -d grant_type=authorization_code -d code=MQCbtKe...44KN -d redirect_uri=https%3A%2F%2Fwww.foo.com%2Fauth https://accounts.spotify.com/api/token

It return error json message and complaining invalid client.

When I remove data it return that error html page.

curl -H "Authorization: Basic ZjM...zE=" https://accounts.spotify.com/api/token

So I assume that in my code the problem is same or something similar. So is it ok to set those parameters to POST call body? It seems that spotify endpoint doesn't get my parameters at all and that is why it doesn't return error message. Here is example provided by spotify and here here is documentation of Angular http component.

Here is my TypeScript call:

var data  = {
    redirect_uri: this.config.redirectUri,
    grant_type: 'authorization_code',
    code : code
};

let headers = this.getTokenHeaders();
let address = "https://accounts.spotify.com/api/token";
return this.http.post(address,data, new RequestOptions({headers: headers}))
    .toPromise()
    .then(res => 
    {
        let body = res.json();
        localStorage.setItem('spotify-access-token', body.access_token);
        localStorage.setItem('spotify-refresh-token', body.refresh_token);
        var expiresIn = body.expires_in;

        return true;
    })
    .catch(err=> 
    {
        return false;
    });

getTokenHeaders()
    {
        return new Headers(this.accountAuth());
    }

private accountAuth(): Object {
    var auth = {
        'Authorization': 'Basic ' + (new Buffer(this.config.clientId + ':' + this.config.clientSecret).toString('base64')),
        'Content-Type': 'application/x-www-form-urlencoded'
        //'Content-Type':'application/json'
    };
    return auth;
}

I have tried to set Content-Type to application/json and application/x-www-form-urlencoded.

1

1 Answers

0
votes

I found this answer https://stackoverflow.com/a/28406268/8081009 and tried it from server side and got same error page there as well when I used message body for delivering parameters. Then I changed parameters to url like this:

var url = "/api/token?redirect_uri=http://localhost:8080/callback.html&grant_type=authorization_code&code="+code;

Now I'm getting correct message. Hopefully this help someone.

So don't use api/token from client side and set parameters to url.