I am trying to use OAuth authentication to get the Salesforce Authentication Token, so I referred wiki docs, but after getting authorization code, when I make a Post request with 5 required parameters, I'm getting following exception
{"error":"invalid_grant","error_description":"authentication failure"} CODE 400
JSON = {"error":"invalid_grant","error_description":"authentication failure"}
which is I guess a bad request.
PostMethod post = new PostMethod("https://login.salesforce.com/services/oauth2/token");
post.addParameter("code",##############);
post.addParameter("grant_type","authorization_code");
post.addParameter("redirect_uri","#################");
post.addParameter("client_id",this.client_id);
post.addParameter("client_secret",this.client_secret);
httpclient.executeMethod(post);
String responseBody = post.getResponseBodyAsString();
System.out.println(responseBody+" CODE "+post.getStatusCode());
Kindly reply, if exception known?
TL:DR
For OAuth 2 tokens if you login...
login.salesforce.com
use https://login.salesforce.com/services/oauth2/tokentest.salesforce.com
use https://test.salesforce.com/services/oauth2/tokenStory:
When I'd call
curl https://login.salesforce.com/services/oauth2/token -d "...credentials..."
it still failed with:{"error":"invalid_grant","error_description":"authentication failure"}
Solution:
Realized there are different OAuth environments when reading Digging Deeper into OAuth 2.0 in Salesforce specifically (emphasis added):
Fix
Because I logged into my environment via
test.salesforce.com
switching tocurl https://test.salesforce.com/services/oauth2/token -d "...credentials..."
resulted in a "Congrats! (>^_^)> Give OAuth token response"To whitelist an IP address range follow these steps:
Setup
in the top-rightAdminister
>Security Controls
>Network Access
from the left navigationNew
Save
Replace your Salesforce password with combination of the password and the security token. For example, if your password is "MyPassword" and your security token is "XXXXXX", you would need to enter "MyPasswordXXXXXX" in the password field.
If you do not have the security token you can reset it as below.
I had the same error with all keys set correct and spent a lot of time trying to figure out why I cannot connect.
Finally I've found that in Setup -> Manage Connected Apps -> Click "MyAppName" -> Click "Edit Policies".
In the 'Permitted Users' field value "All users may self-authorize" should be set.