[SalesForce] Issues with connected App – {“error_description”:”authentication failure”,”error”:”invalid_grant”}

I've successfully implemented the oAuth2 authentication process using the Web Server Flow of the REST API between my application and Salesforce, and it's working great when connecting with a Developer Edition type Salesforce account.

However, it's not working when trying to connect a test or prod environment type Salesforce account: I can't get an access token with the authorization code given by Salesforce since Salesforce gives me this error:

{"error_description":"authentication failure","error":"invalid_grant"}

Does anybody have an idea why it's not working ?

Here's what I've done:

Step 1 => OK => Redirect user to Salesforce

Step 2 => OK => User logs in

Step 3 => OK => User is redirected to our application with the authorization code

Step 4 => NOT OK => We request an access token using the authorization code given by Salesforce

We have tried it all (maybe not though :D): we have checked all the security configuration on our end and on the customer's end, we have checked for IP restrictions (no IP restriction is used), we have given our App "Full Access", but still no luck. We are receiving the authorization code which is encoded correctly and seems normal.

Does anybody have an idea why it's not working ?

Do you know if I need to validate our connected App before it can be used by test or prod type Salesforce accounts ?

Thanks a lot for all your help in advance.
Cheers
Quentin

NOTE : This is a duplicate of the following issue I guess, but it got no answer šŸ™ https://developer.salesforce.com/forums?id=906F00000009AFvIAM

EDIT 1 :

Here's the code I use ($instance is 'https://test.salesforce.com' in our case):

    $url = $instance . '/services/oauth2/token?format=json';
    $postFields = array(
        'code' => $code,
        'grant_type' => 'authorization_code',
        'client_id' => $this->clientId,
        'client_secret' => $this->clientSecret,
        'redirect_uri' => $this->redirectURL);
    // Create the CURL object.
    $handle = curl_init($url);
    curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($handle, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($handle, CURLOPT_POST, TRUE);
    curl_setopt($handle, CURLOPT_POSTFIELDS, $postFields);

Best Answer

I feel pretty dumb answering my own question but that may help somebody someday.

@Rao was totally right about that one so he deserves all the credit.

In my "Edit 1", I was wrong about the content of $instance.

It was not pointing to 'https://test.salesforce.com', it was pointing to 'https://login.salesforce.com' so it was normal to get an "authentication failure" error.

So if you're experiencing the same problem, do check the URL you're sending the request to.

Related Topic