0 votes
1 view
in Salesforce by (11.9k points)

I am receiving a 400 bad request when using Google OAuth from within Salesforce. The following error is in regards to invalid grant_type, but if you look at the documentation under 'Using Refresh Token' you will see that it is correct.




 "error": "unsupported_grant_type",

 "error_description": "Invalid grant_type: "


I am attempting to exchange a refresh_token for an access token and can successfully do it using CURL, with the following code.

curl \
  -d refresh_token=REFRESH_TOKEN \
  -d client_id=CLIENT_ID \
  -d client_secret=CLIENT_SECRET \
  -d grant_type=refresh_token https://www.googleapis.com/oauth2/v4/token

The code that I am using inside Salesforce:

 Http http = new Http();
    HttpRequest req = new HttpRequest();
    req.setHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    req.setHeader('Content-Length', '0');
    req.setHeader('client_id', 'CLIENT_ID');
    req.setHeader('client_secret', 'CLIENT_SECRET');
    req.setHeader('refresh_token', 'REFRESH_TOKEN');
    req.setHeader('grant_type', 'refresh_token'); 
    return http.send(req);

1 Answer

0 votes
by (31.8k points)

The option: -d curl conveys the data in the request body using the application/x-www-form-urlencoded content type which is one of the supported ways of sending those parameters in OAuth2.

-d Sends the specified data in a POST request to the HTTP server, in the same way that a browser does when a user has filled in an HTML form and presses the submit button. This will cause curl to pass the data to the server using the content-type application/x-www-form-urlencoded.

In the Salesforce code you're installing the correct content type, but then are sending the OAuth2 related parameters as additional headers instead of sending them in the request body.

You need to update the code to send the parameters in the request body using the application/x-www-form-urlencoded encoding.

Welcome to Intellipaat Community. Get your technical queries answered by top developers !