-4

I am trying to exchange my authorizatoin code for an access token. I keep getting a "request parameters are malformed" error. I can curl the endpoint just fine but for some reason I can't get a valid response in the server.

Here is the code I am using:

 public TikTokTokenResponse getTiktokAccessToken(String code, String redirectUrl) throws Exception {
    URI uri = new URI(String.format("https://open.tiktokapis.com/v2/oauth/token/"));

    MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
    body.add("client_key", tiktokClientKey);
    body.add("client_secret", tiktokClientSecret);
    body.add("code", code);
    body.add("grant_type", "authorization_code");
    body.add("redirect_uri", redirectUrl);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    headers.setCacheControl("no-cache");

    HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(body, headers);

    log.info("Getting tiktok access token " + uri.toString());
    return restTemplate.postForObject(uri, requestEntity, TikTokTokenResponse.class);
}

1 Answer 1

1

After a lot of trial and error I figured out the problem. In comparing my postman and curl requests that were working I noticed that they weren't url encoding the code. And after reviewing the documentation for tiktok I noticed it said the code value should be URL decoded. So looking at my spring boot request above I realized by default it url encoded all the parameters. So I built the request body manually to avoid this and finally it worked! See code below:

public TikTokTokenResponse getTiktokAccessToken(String code, String redirectUrl) throws Exception {
    URI uri = new URI(String.format("https://open.tiktokapis.com/v2/oauth/token/"));

    //Manually construct the body to prevent URL-encoding of the 'code' parameter
    String body = "client_key=" + URLEncoder.encode(tiktokClientKey, StandardCharsets.UTF_8) +
            "&client_secret=" + URLEncoder.encode(tiktokClientSecret, StandardCharsets.UTF_8) +
            "&grant_type=authorization_code" +
            "&redirect_uri=" + URLEncoder.encode(redirectUrl, StandardCharsets.UTF_8) +
            "&code=" + code;

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    headers.setCacheControl("no-cache");

    HttpEntity<String> requestEntity = new HttpEntity<String>(body, headers);

    log.info("Getting tiktok access token " + uri.toString());
    return restTemplate.postForObject(uri, requestEntity, TikTokTokenResponse.class);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.