Salesforce API — authentication
Recently I spent some time in a free Salesforce developer sandbox on Force.com. I got to experimenting with their API to connect with my little custom app and realised there were a few gotchas along the way that required some investigation. This post is an aide-mémoire for me, but may help others in similar circumstances.
You need to set a few config settings in the Force.com UI in order to authenticate using the Salesforce API:
- ensure ‘all users may self-authorise’
- ensure IP range is set (or relaxed)
Then, in name > personal, select ‘reset security token’ to get emailed your token. Append this to your password when authenticating with the API:
curl https://login.salesforce.com/services/oauth2/token -d "grant_type=password" -d "client_id=<YOUR_CLIENT_ID" -d "client_secret=<YOUR_SECRET>" -d "username=<YOUR_USERNAME>" -d "password=<YOUR_PASSWORD><YOUR_TOKEN>"
…which returns:
{"access_token":"<YOUR_ACCESS_TOKEN>", "instance_url":"https://eu11.salesforce.com","id":"https://login.salesforce.com/id/00GFW000000ccwwUAA/0079400000v3GWQAY","token_type":"Bearer","issued_at":"1498045747558","signature":"Bz8JWOVDvr1hN1e8zd/wVwqwerbj3cDAcPcO7QrUmGo="}
You can then make requests like:
curl https://eu11.salesforce.com/services/data/v37.0/ -H "Authorization: Bearer <YOUR_ACCESS_TOKEN>" -H "X-PrettyPrint:1"
Just remember to escape the ! character in your access token.