function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
jeffdonthemic2jeffdonthemic2 

Obtaining Access Token using cURL?

While the API docs have a lot of great examples using cURL, I don't see an example of how to actually obtain the access token. I tried the following with no joy:

 

 

curl grant_type=authorization_code \
  client_id=MY-CONSUMER-KEY \
  client_secret=MY-CONSUMER-SECRET \
  https://na5.salesforce.com/services/oath2/token

 

 

Thanks

 

Jeff Douglas

Appirio, Inc.

http://blog.jeffdouglas.com

 

Author: The Salesforce Handbook

codesciencecodescience

Having read little of the docs, I'll spout off anyhow:

 

I believe that is generated as part of the Remote Access set up process within your SFDC org prior to using the REST API service from curl, etc. Also, from the webinar, I believe it was mentioned a valid/active session ID will also suffice. Not sure how that plays with the client_secret except perhaps it can be null when using the SID.

 

Tim

jeffdonthemic2jeffdonthemic2

You obtain the access token by posting the token and token secret and force.com returns the access token that is used for subsequent calls. If you look at the Java code in the API doc you can see how to obtain an access token but it requires the redirect url which is not available in terminal.

 

You can do the same thing with the FB Graph API from terminal. You curl this and it returns an access token that you paste into subsequent calls.

 

 

curl -F grant_type=client_credentials \
     -F client_id=app-id \
     -F client_secret=app-secret \
     https://graph.facebook.com/oauth/access_token

 

I'm hoping that Alex just left this part out of the documentation by mistake.

 

 

Jeff Douglas

Appirio, Inc.

http://blog.jeffdouglas.com

 

Author: The Salesforce Handbook

Mysti, Developer DocumentationMysti, Developer Documentation

The doc is a pilot doc, so not as complete as for GA. I'll *definitely* incorporate this, thank you!

jeffdonthemic2jeffdonthemic2

Can post the cURL command here so we can utilize it? Perhaps I wasn't clear in my first post that I can't find the actual cURL command anywhere on how to get the access token.

 

Thanks

Jeff

gwestrgwestr

You can use your Salesforce.com session ID or SID wherever it says "token" in the documentation.

 

There are two ways to get it.  I think you were trying to do this way first, but were using grant_type of "token" instead of "password":

 

curl -v https://na7.salesforce.com/services/oauth2/token -d "grant_type=password" -d "client_id=xxxxxxxxxx" -d "client_secret=1234567890" -d "username=noreply@salesforce.com" -d "password=XXXXXXXXX"

 

Obviously, you have to replace na7 with your instance, the consumer key (client_id), consumer secret (client_secret), username and password.

 

Before OAuth2, Web Services API developers and Bulk API developers would make a SOAP envelope:

 

<?xml version="1.0" encoding="utf-8" ?> <env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">

<env:Body>

<n1:login xmlns:n1="urn:partner.soap.sforce.com">

<n1:username>your_username</n1:username>

<n1:password>your_password</n1:password>

</n1:login>

</env:Body>

</env:Envelope>

 

And send it to:

 

curl https://login.salesforce.com/services/Soap/u/20.0 -H "Content-Type: text/xml; charset=UTF-8" -H "SOAPAction: login" -d @login.txt

 

And this is still a valid way of logging in and getting a SID.

SuperfellSuperfell

As Greg mentions, the username password oAuth2 flow is the easiest way to get an access token if your trying stuff out from the command line. this returns a structure like this

 

 

{"id":"https://login.salesforce.com/id/00D300000000QSf/00530000000dImz","issued_at":"1288235704223","instance_url":"https://na1.salesforce.com","signature":"zAUjvvB2RaGv+nzfPNi21Q1E813/G0FkONPFOVhcRro=","access_token":"some token"}

 

You can then take the access_token value and use it as the token/sid for the rest api calls.

 

In addition, you can send the username/password request to login.salesforce.com/services/oauth2/token, you don't need to know the users instance in advance. And similar to the soap login response, you can see in the above response the base instance url.

 

The other item of interest, is the identity Url, this will (via a redirect), return a bunch of info about the user, similar to soap's getUserInfo, and also URLs to photos, and URL patterns for other APIs, worth a look if you haven't seen it yet.

 

emacadieemacadie

I have a few questions.

 

1. Is my SID the same username/password I use to log into the website?

 

2. For this command:

curl -v https://na7.salesforce.com/services/oauth2/token -d "grant_type=password" -d "client_id=xxxxxxxxxx" -d "client_secret=1234567890" -d "username=noreply@salesforce.com" -d "password=XXXXXXXXX"

 

What is my instance?

emacadieemacadie
 Posted by jeffdonthemic2 
 on 10-27-2010 08:04 AM:

You obtain the access token by posting the token and token secret and force.com returns the access token that is used for subsequent calls. If you look at the Java code in the API doc you can see how to obtain an access token but it requires the redirect url which is not available in terminal.

 

Could someone explain what jars the Java code depends on?  I am looking at the code at http://www.salesforce.com/us/developer/docs/api_rest/index.htm in the Getting Started with the Force.com REST API/Quick Start/Step Two: Set Up Authorization section, and I do not see any import statements. What is being used in this code?

 

Mysti, Developer DocumentationMysti, Developer Documentation

Answering emacadie:

 

Your 2nd question first, in the example "na7" is the instance name.

 

Answering your question #1. The session ID (SID) is generated when you log in to the website, but it is not the same value as your username and password. Here's the info from the REST doc:

 

Session ID Authorization

You can use a session ID instead of an OAuth 2.0 access token if you aren't handling someone else's password:
  1. Obtain a session ID, for example, a SOAP Web services APIlogin() call returns the session ID. You may also have the session ID, for example as part of the Apex current context.
  2. Use the session ID when you send a request to the resource. Substitute the ID for the token value. The syntax is the same:
     Authorization: OAuth token

    For example:

     curl https://instance_name.salesforce.com/services/data/v20.0/ -H "Authorization: OAuth token"
gitguygitguy

What is the client_id value supposed to be?  Where's that value come from?

gitguygitguy

Never mind.  It's the consume key.

 

The question is, if the client application doesn't have a call-back, is it ok to use a bogus callback url for the client?  I mean, if I'm doing everything from curl then there isn't anywhere to callback to.

zachelrathzachelrath

I think that the "Session ID Authorization" section, part 1 (starting with "Obtain a Session Id"), of the REST API Dev Guide OAuth Setup Step 2, should specify the CURL url as instance_name.salesforce.com , NOT login.salesforce.com 

 

As this and other Developer Board posts indicate, trying to obtain a Session Id from login.salesforce.com FAILS, but if you hit instance_name.salesforce.com, usually with the error

 

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

 

BUT, it SUCCEEDS when you point at instance_name.salesforce.com. Is this a bug? Or are the docs wrong?

 

**EDIT**: Salesforce has confirmed that this a bug. Until it is resolved, the following instructions will work:

 

1. Obtain a session ID, for example, a SOAP API login() call returns the session ID. You may also have the session ID, for example as part of the Apex current context. If you need a session ID just for testing purposes during development, you can use the username-password OAuth flow in a cURL command similar to the following:

curl https://<instance>.salesforce.com/services/oauth2/token -d "grant_type=password" -d "client_id=myclientid" -d "client_secret=myclientsecret" -d "mylogin@salesforce.com" -d "password=mypassword123456"

 

Regards,

 

Zach McElrath

SuperfellSuperfell

The docs are correct, token requests should goto login.salesforce.com (or test.salesforce.com for sandbox), not the instance. If you are seeing issues related to token requests when sent to login.salesforce.com that's a bug, please log a case with support.

SuperfellSuperfell

This is a bug, am working to get it published on the known issues list for you to follow.

zachelrathzachelrath

Thanks Simon!

venkatesh.umaashank1.3883524493878723E12venkatesh.umaashank1.3883524493878723E12
Hi I am totally new to salesforce.com, I have registered as a user for developer edition. I want to access the data in salesforce through rest api. I have created a connect app, now I have key and secret. But what I do not understand is how do i get the instance name / url to which I cant send my authorization request to get the OATH token? Any suggestions will be very helpful.
Beatriz RamírezBeatriz Ramírez
Hi i wish to know if someone has an experience to use curl as gwestr mentioned but using an org who have the sso. I try with the suggested code but I got this error
<?xml version="1.0" encoding="UTF-8"?> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sf="urn:fault.partner.soap.sforce.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Body><soapenv:Fault> <faultcode>INVALID_LOGIN</faultcode> <faultstring>INVALID_LOGIN: Invalid username, password, security token; or user locked out.</faultstring> <detail><sf:LoginFault xsi:type="sf:LoginFault"> <sf:exceptionCode>INVALID_LOGIN</sf:exceptionCode><sf:exceptionMessage>Invalid username, password, security token; or user locked out.</sf:exceptionMessage></sf:LoginFault></detail></soapenv:Fault></soapenv:Body></soapenv:Envelope>


curl -v https://na7.salesforce.com/services/oauth2/token -d "grant_type=password" -d "client_id=xxxxxxxxxx" -d "client_secret=xxxxxxx" -d "username=XXXXX@acme.com" -d "password=XXXXXXXXX"

Please Help me !!!
Jordan SewellJordan Sewell

I successfully got an oauth token using curl in my linux terminal (make sure you have set up the remote access/connected app settings).

curl -X POST -F "grant_type=password" -F "client_id=[CLIENT ID FROM REMOTE ACCESS]" -F "client_secret=[CLIENT SECRET FROM REMOTE SETTINGS]" -F "username=[YOUR UN]" -F "password=[YOUR PASSWORD]" https://login.salesforce.com/services/oauth2/token

Then here is the response:
{
  "access_token": "[TOKEN for subsequent api requests]",
  "instance_url": "https://[your instance].salesforce.com",
  "id": "https://login.salesforce.com/id/[ORGID]/[USERID]",
  "token_type": "Bearer",
  "issued_at": "1492463040918",
  "signature": "[SIGNATURE]"
}

If you need to do a SOAP call see below (which you don't need to have the Oauth settings configured, but you will need to whitelist your IP or include your token)

ENDPOINT: https://login.salesforce.com/services/Soap/u/22.0

Method: POST

Headers:
Content-Type: text/xml;charset=UTF-8
SOAPACTION: ""

Body:
<?xml version="1.0" encoding="UTF-8"?>
<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
   <Header />
   <Body>
      <login xmlns="urn:partner.soap.sforce.com">
         <username>[username]</username>
         <password>[password][security token]</password>
      </login>
   </Body>
</Envelope>

Response:
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns="urn:partner.soap.sforce.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <soapenv:Body>
        <loginResponse>
            <result>
                <serverUrl>https://[YOUR INSTANCE].salesforce.com/services/Soap/u/22.0/00D4C0000000nCR</serverUrl>
                <sessionId>[TOKEN FOR SUBSEQUENT REQUESTS]</sessionId>
            </result>
        </loginResponse>
    </soapenv:Body>
</soapenv:Envelope>

There is a lot more information in the soap response but you really only need the 2 I included. Notice that the "SOAPACTION" header is a blank string...I don't know why that is but if you don't include the header the login fails.
Both of these methods work and as long as you include the header "Authorization = Bearer [TOKEN]" you should be able to hit the REST/SOAP/custom apex rest apis available to your user in that org
Dilpesh BadarshahiDilpesh Badarshahi

Hi
I want to integrate with one of my project for multiple users is it possible to do not ask for password to get bearer token for making call of all REST Api using any other detail like client_key or client_secret?

Please answer if possible 

Srinivasu BonguSrinivasu Bongu
Hello,

I am trying to automate creating tickets in Salesforce. For this, I am using API with Python. I have got the Client ID and Client secret for my registered python Application. I have read many questions and as per the security purpose, I do not want to use the "user-password" flow for my script. Is there anyway that I can only use "CLIENT ID" and "CLIENT SECRET" to get the access token where I can pass this access token in bearer header for other calls

https://developer.salesforce.com/forums/ForumsMain?id=9062I000000XlXzQAK
Sanjay SubramanianSanjay Subramanian
Hi all

To set the context for my questions, I am doing all the following accessing my Salesforce sandbox

1. When I tried gwestr's CURL example from above to get the access token, the curl gave me a lot of verbose output. ? I could not figure out the access token from the verbose output.

2. Following the OAuth 2.0 Username-Password Flow for Special Scenarios (https://help.salesforce.com/articleView?id=remoteaccess_oauth_username_password_flow.htm&type=5) doc I tried a post request using POSTMAN (running on a Mac)
https://XXX123.lightning.force.com/services/oauth2/token?grant_type=password&client_id=MY_CONSUMER_KEY&client_secret=MY_CONSUMER _SECRET&username=MY_USER_NAME&password=MY_PASSWORD
The response I get in POSTMAN is as follows (albeit I a using POST)
{
    "error": "invalid_request",
    "error_description": "must use HTTP POST"
}



3. I tried POST in Python (Anaconda Python 3.8.x) intwo ways. Here is my code 
import requests

url = 'https://XXX123.lightning.force.com/services/oauth2/token'

url2 = 'https://XXX123.lightning.force.com/services/oauth2/token?grant_type=password&client_id=MY_CONSUMER_KEY&client_secret=MY_CONSUMER_SECRET&username=MY_USER_NAME&password=MY_PASSWORD'

myobj = {
   'grant_type' : 'password',
   'client_id' : 'MY_CONSUMER_KEY',
   'client_secret' : 'MY_CONSUMER_SECRET',
   'username' : 'MY_USER_NAME',
   'password' : 'MY_PASSWORD'}

x1 = requests.post(url, data = myobj)
print("Response when sending POST request with a BODY")
print(x1.text)

print("")

x2 = requests.post(url2)
print("Response when sending POST request WITHOUT a BODY")
print(x2.text)

The python code response is as follows:
Response when sending POST request with a BODY
{"error":"unsupported_grant_type","error_description":"grant type not supported"}

Response when sending POST request WITHOUT a BODY
{"error":"invalid_request","error_description":"must use HTTP POST"}

Thoughts? Thanks for your time.


 
Joe CaponiJoe Caponi
Spent some time this afternoon struggling to get an access token via curl - this is what finally worked for me. Please watch out to include your proper instance and especially, to include your security token appended to your password. Security token available from your top-right photo - settings - reset my security token.
curl -v https://[INSTANCE].salesforce.com/services/oauth2/token -d "grant_type=password" -d "client_id=[CLIENTID]" -d "client_secret=[SECRET]" -d "username=[USERNAME]" -d "password=[PASSWORD][SECURITYTOKEN]"
Good luck!
 
KushiKushi
How can we insert an attachment on Case record using cURL? I have tried the below but no luck - 
curl  https://test.salesforce.com/services/data/v52.0/sobjects/Case/recordid/Files -H 'Authorization: Bearer xxxxxx' -H "Content-Type: image/jpeg" --data-binary @output.txt