bad token + no refresh token on spotify api

Viewed 246

i'm making an application with the spotify API, when I try to get te access token and the refresh token I have a problem. On the json response I don't have any refresh token and the given access token does not work (way too short in comparison on the one I get directly on the spotify website. Please tell me if you see something wrong on it (The spotify abi is based on Oauth2.0)

Here is my code


        try {
            String urlString = "https://accounts.spotify.com/api/token?";

            URL website = new URL(urlString);

            HttpURLConnection connection = (HttpURLConnection) website.openConnection();
            connection.setRequestMethod("POST");


            // Headers
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            connection.setDoOutput(true);

            // Add parameters to the body
            HashMap<String, String> params = new HashMap<>();
            params.put("grant_type", "client_credentials");
            params.put("redirect_uri", ID.REDIRECT_URI);
            params.put("code", code);
            params.put("client_id", ID.CLIENT_ID);
            params.put("client_secret", ID.CLIEN_SECRET_ID);

            OutputStream os = connection.getOutputStream();
            BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, StandardCharsets.UTF_8));
            writer.write(getPostDataString(params));
            writer.flush();
            writer.close();
            os.close();

            // Open the connection
            connection.connect();

            JsonObject jsonResponse  = Http.statusResponse(connection);

            // Close the connection
            connection.disconnect();

            System.out.println(jsonResponse);
            return jsonResponse;


        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

This is what I get:

{"access_token":"BQAQxzMFIqOY2vk9aWintAgOilaY77N6s-xL2nyHmVzWMsnu4t3wmvGJ-EK_2MDMXvniBEeYoydvbYZpxOY","token_type":"Bearer","expires_in":3600}

This is what I should get (based on the spotify guide : https://developer.spotify.com/documentation/general/guides/authorization/code-flow/)

{ "access_token": "NgCXRK...MzYjw", "token_type": "Bearer", "scope": "user-read-private user-read-email", "expires_in": 3600, "refresh_token": "NgAagA...Um_SHo" }

1 Answers

Your grant_type parameter should be authorization_code instead of client_credentials. The client_credentials grant type does not give access to authorization scopes.

So use params.put("grant_type", "authorization_code");

Hope that helps!

Related