88

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?

crenshaw-dev
  • 7,504
  • 3
  • 45
  • 81
Vardan Gupta
  • 3,505
  • 5
  • 31
  • 40

13 Answers13

222

For anyone who is as stuck and frustrated as I was, I've left a detailed blog post on the entire process (with pictures and ranty commentary!). Click the link if you want that:

http://www.calvinfroedge.com/salesforce-how-to-generate-api-credentials/

Here is a text only answer:

Step 1:

Create an account. You can create a (free) developer account at developer.salesforce.com


Step 2:

Ignore all the landing pages and getting started crap. It's an endless marketing loop.


Step 3:

Click the "Setup" link


Step 4:

In the lefthand toolbar, under "Create", click "Apps"


Step 5:

Under "Connected Apps" click "New"


Step 6:

Fill out the form. Important fields are the ones marked as required, and the oauth section. Note that you can leave any url for your callback (I used localhost).


Step 7:

Be advised that Salesforce has crappy availability.


Step 8:

Press continue. You finally have your client_id key (labelled 'Consumer Key') and client_secret (labelled 'Consumer Secret').


Step 9:

But wait! You're not done yet; select 'Manage' then 'Edit Policies'

  1. Make sure IP relaxation is set to Relax IP restrictions,

  2. and make sure that Permitted Users is set to "All users may self-authorize.",

  3. and also make sure the your Security > Network Access > Trusted IP Ranges has been set

OAuth settings

Security > Network Access > Trusted IP Ranges

If you're concerned about disabling security, don't be for now, you just want to get this working for now so you can make API calls. Tighten permissions once you have everything working, one at a time, so you can figure out what setting is giving you authentication errors.


Step 10:

Celebrate! This curl call should succeed:

on production:

curl -v https://login.salesforce.com/services/oauth2/token \
  -d "grant_type=password" \
  -d "client_id=YOUR_CLIENT_ID_FROM_STEP_8" \
  -d "client_secret=YOUR_CLIENT_SECRET_FROM_STEP_8" \
  -d "username=user@wherever.com" -d "password=foo@bar.com"

on sandbox or test:

curl -v https://test.salesforce.com/services/oauth2/token \
  -d "grant_type=password" \
  -d "client_id=YOUR_CLIENT_ID_FROM_STEP_8" \
  -d "client_secret=YOUR_CLIENT_SECRET_FROM_STEP_8" \
  -d "username=user@wherever.com" -d "password=foo@bar.com"

Notes:

  • You shouldn't be doing password authorization if you're building a multi-tenant app, where users need to authorize their own application. Use the Oauth2 workflow for that.

  • You may need to pass in your security token appended to your password.

Martin of Hessle
  • 394
  • 3
  • 12
Calvin Froedge
  • 16,135
  • 16
  • 55
  • 61
  • glad i made it all the way to Step 10, good call with the CURL debugging – Wes Johnson Mar 18 '15 at 18:47
  • 15
    Wow...Thanks a lot...Step 9 is simply superb which pulled me out of struggle – Azeez Jun 03 '15 at 19:01
  • 7
    Do we need to pass security token with password on using OAuth login ? I am getting same error `invalid_grant` – Dory Jul 22 '15 at 08:31
  • 2
    Great guide and it almost worked for me. The problem i got is that the url used in step 10 did not work because we have a subdomain. .my.saleforce.com. Hopefully no one else have do waste time on this. – Mikael Svensson Apr 12 '16 at 08:02
  • 7
    my issue was after all that your password can't contain certain special characters! wtg sf! – john.stein Dec 09 '16 at 14:53
  • 1
    Changes as of Aug 2017: 1. In step 4, The "New Connected App" button is under Apps -> App Manager. 2. In step 9, I had to set up an actual trusted IP range. – aldel Aug 03 '17 at 02:49
  • Does anyone have any clue where to get the security token? salesforce is so confusing. – Dan Zuzevich Aug 30 '17 at 16:57
  • 1
    @DanielZuzevich I found it by clicking the "me" icon at the top-right, selecting Settings, and then going to "Reset My Security Token" in the left sidebar. – crenshaw-dev Oct 05 '17 at 12:57
  • 2
    Step 9 worked for me as well; specifically, setting "Permitted Users" to "All users may self-authorize." Thank you! – Ryan Burney Jan 04 '18 at 20:59
  • 2
    Hallelujah!!! Thank you very much. Salesforce needs to take note - their documentation really needs improving. – Channing Walton Jun 18 '18 at 09:55
  • I followed all the above steps but was still getting the invalid grant error, but in the user access log it said invalid password, even though I was using the correct password with the security token appended. Turned out my user didn't have sufficient permissions. So I just created a new user as the System Administrator profile and it all worked nicely :) Hope this helps somebody else – Harry12345 Aug 03 '18 at 14:35
  • 4
    Thanks so much, I keep coming back to this process every time I need to find that page. Can't believe how hard it is to navigate salesforce. – User128848244 Oct 22 '18 at 15:34
  • @Brandt me too .. :) I am coming back to this answer everytime to solve the issue.. Everytime I try to upvote this answer , but I have already voted for it earlier :) – Kamal Feb 01 '19 at 10:11
  • Solve for special characters in login: use SOAP login described in the Bulk API Developer Guide > Quickstart where the login info is reference in a file like this: curl https... -H "Content-Type: text/xml; charset=UTF-8" -H "SOAPAction: login" -d @login.txt – joynoele Feb 04 '19 at 20:59
  • 4
    Blog seems to be dead - archived copy here https://web.archive.org/web/20181226011555/http://www.calvinfroedge.com/salesforce-how-to-generate-api-credentials/ – CupawnTae Dec 02 '19 at 13:28
  • 1
    FWIW I had to do one thing differently. Some of these views were not accessible to me in the "Lighting" UI but I was able to do it in the "Classic" UI. Not sure why. Maybe this will help someone else. – Mike Vosseller Dec 26 '19 at 18:25
  • is the process same for SandBox account ?? – Dave Jan 06 '21 at 13:51
  • Just an FYI for new people. If you wanna follow this guide you must switch to "Salesforce Classic" mode. You can do this by clicking on your profile bubble at the top right of your screen. Why Salesforce is the way it is has yet to be determined. – Noah Gary Jan 12 '21 at 21:43
  • Thanks for step 7. If only we could get the execs to read this before buying. – mjaggard Sep 15 '22 at 07:00
14

We had this issue as well.

Check your Connected App settings - under Selected OAuth Scopes, you may need to adjust the selected permissions. Our app primarily uses Chatter, so we had to add both:

  • Access and manage your Chatter feed (chatter_api)
  • Perform requests on your behalf at any time (refresh_token).

Again, your mileage may vary but try different combinations of permissions based on what your Application does/needs.

Additionally, the actual invalid_grant error seems to occur due to IP restrictions. Ensure that the server's IP address that is running the OAuth authentication code is allowed. I found that if the SFDC environment has IP restriction setting Enforce IP restrictions set (Setup -> Administer -> Manage Apps -> Connected Apps), then each User Profile must have the allowed IP addresses as well.

Paul T. Rawkeen
  • 3,994
  • 3
  • 35
  • 51
dotNetkow
  • 5,053
  • 4
  • 35
  • 50
  • 3
    Thanks... I had the same issue. The default for app is "Enforce IP Restriction" so you do need to relax this in Setup -> Administer -> Manage Apps -> Connected Apps... as above. – dacology Jun 18 '14 at 13:51
13

TL:DR

For OAuth 2 tokens if you login...

Story:

  1. I was following Salesforce "Set Up OAuth 2.0"
  2. Credentials were correct (many character by character checks)
  3. 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):

OAuth 2.0 Authentication Endpoints

OAuth endpoints are the URLs that you use to make OAuth authentication requests to Salesforce. When your application makes an authentication request, make sure you’re using the correct Salesforce OAuth endpoint. The primary endpoints are:

Instead of login.salesforce.com, customers can also use the My Domain, community, or test.salesforce.com (sandbox) domains in these endpoints.

Fix

Because I logged into my environment via test.salesforce.com switching to curl https://test.salesforce.com/services/oauth2/token -d "...credentials..." resulted in a "Congrats! (>^_^)> Give OAuth token response"

3ygun
  • 1,192
  • 12
  • 14
7

To whitelist an IP address range follow these steps:

  1. Click Setup in the top-right
  2. Select Administer > Security Controls > Network Access from the left navigation
  3. Click New
  4. Add your ip address range
  5. Click Save
Troy Harvey
  • 2,331
  • 1
  • 20
  • 18
7

Salesforce is requiring an upgrade to TLS 1.1 or higher by July 22, 2017 in order to align with industry best practices for security and data integrity: from help.salesforce.com.

try to add this code:

System.Net.ServicePointManager.SecurityProtocol = 
SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

Another option is to edit your registry:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

Check this link for more detailed answers: Default SecurityProtocol in .NET 4.5

Community
  • 1
  • 1
Amir M
  • 508
  • 1
  • 8
  • 28
  • Related github issue for a salesforce oauth provider https://github.com/TerribleDev/OwinOAuthProviders/issues/177 – Ben Wilde Sep 28 '17 at 19:05
6

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.

  • Go to Your Name --> My Settings --> Personal --> Reset My Security Token.
Satish
  • 71
  • 1
  • 2
3

You can call your APEX controller using Postman if you enter the Consumer Key and Consumer Secret in the Access Token settings - you don't need the Security Token for this.

Set up the Authorization like this screenshot...

Postman OAuth 2.0

And enter your credentials on the window after hitting the Get New Access Token button...

Get Access Token

Then hit the Request Token button to generate a token, then hit the Use Token button and it will populate the Access Token field on the Authorization tab where you hit the Get New Access Token button.

Kevin
  • 121
  • 1
  • 4
  • 1
    Welcome to Stackoverflow, Explain your answer in detail with steps or code snippet if any, so that it will be helpful for everyone to understand. – Şivā SankĂr Jan 29 '19 at 11:51
  • updated original post with further instructions and another screenshot – Kevin Jan 30 '19 at 14:52
  • 1
    I can't thank you enough for posting your instructions on retrieving the access token with Postman. The "Quick Start" instructions in the Salesforce "REST API Developer Guide" are unfortunately less than worthless when it comes to configuring Salesforce and retrieving the Access Token that is required for ALL of their CURL commands (Authorization: Bearer ). – jerhewet Feb 28 '20 at 17:28
1

I was banging my head against the desk trying to get this to work. Turns out my issue was copying and pasting, which messed up the " character. I went and manually typed " pasted that into the command line and then it worked.

Andronicus
  • 25,419
  • 17
  • 47
  • 88
That Guy
  • 11
  • 1
1

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.

algot
  • 2,428
  • 3
  • 19
  • 23
1

Make sure your password only has alphanumeric characters in it.

Sash
  • 4,448
  • 1
  • 17
  • 31
0

In addition to following the suggestions above, I found that Salesforce didn't like how axios was encoding data as JSON. I switched from the default JSON encoding to using qs to stringify and post as form data and that worked. Still not sure why Salesforce didn't like the JSON version, if anyone has better ideas I'm curious to learn more.

This worked:

axios.post(
  url,
  qs.stringify({
    grant_type: "password",
    username: process.env.USERNAME,
    password: process.env.PASSWORD,
    client_id: process.env.SF_ID,
    client_secret: process.env.SF_SECRET,
  }),
  { headers: "Content-Type": "application/x-www-form-urlencoded", },
)

This didn't:

axios.post(
  url,
  {
    grant_type: "password",
    username: process.env.SF_USERNAME,
    password: process.env.SF_PASSWORD,
    client_id: process.env.SF_ID,
    client_secret: process.env.SF_SECRET,
   }
);
bjorn
  • 116
  • 7
0

I had this problem and after trying several failed tutorials I came across a post that said Salesforce won't accept a password with special characters in it (!, @ ,#). I changed my password in Salesforce to one without special characters and finally got it to work.

bmich72
  • 640
  • 5
  • 6
-1

I tried many solutions above which did not work for me. However the trick that actually worked for me was to stop using curl and to use postman application to make the request instead.

By replicating the request in postman, with a POST request and the following params

  1. grant_type
  2. client_id
  3. client_secret
  4. username
  5. password

This solved the issue for me.

Just posting it here in case there are others who have tried all the possible solutions with no avail (like I did).

Sai
  • 461
  • 7
  • 25