I am trying to send a POST request to https://test.salesforce.com/services/oauth2/token to retrieve the oauth access token. The response is 400 Bad Request with no info. Here's the (Java) client code:

private void authenticate() {
    RestTemplate req = new RestTemplate();        
    JSONObject oauth_req = new JSONObject();
    //JSONObject oauth_res = new JSONObject();

    oauth_req.put("grant_type", "password");
    oauth_req.put("client_id", this.CONSUMER_KEY);
    oauth_req.put("client_secret", this.CONSUMER_SECRET);
    oauth_req.put("username", this.USER);
    oauth_req.put("password", this.PASSWORD);

    String reqToString = oauth_req.toString();       
    HttpHeaders headers = new HttpHeaders();

    HttpEntity<String> entity = new HttpEntity<>(reqToString,headers);
    String res = req.postForObject(TEST_AUTH_URL, entity, String.class);

I have attempted this with both postForObject() and exchange() with the same results. I am certain that the body is correct, as I am able to retrieve the token with Postman. Is it possible that the issue is with my header or entity?

  • See OAuth2 token request using JSON fails - grant type not supported. One problem is that you should be sending in application/x-www-form-urlencoded format not in JSON format.
    – Keith C
    Jun 30, 2015 at 14:59
  • I see. I misunderstood the documentation, the optional "format" parameter is for expected RETURN format. This the answer to my question if you want to post it.
    – wsc
    Jun 30, 2015 at 15:54
  • Yeah I've been there too; now JSON is so popular it's unexpected to have to use form encoding and I don't think the documentation emphasises this as much as it could.
    – Keith C
    Jun 30, 2015 at 16:55


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.