If you are in need of validating a Salesforce API from start to finish using cURL - i.e. from authorization code to access token to a successful API call using the access token - try this:
Create a Connected App in your Salesforce Org:
Check the Salesforce documentation for Create a Connected App with OAuth. Include https://localhost as one of the Callback URLs to follow along with this example, or use whatever URL you like, but just be sure to modify the example below accordingly.
Once you have the Connected App, you can copy-paste the following URL in browser:
Note: If you are attempting to do this in Production, then use 'login' instead of 'test' in the URL.
https://test.salesforce.com/services/oauth2/authorize?client_id=[Consumer Key from Connected App]&response_type=code&scope=api&access_type=offline&redirect_uri=https://localhost
You will be presented with a login screen.
After successfully logging in, your browser will be redirected to https://localhost, which, obviously, will not render a working page, but the authorization code will be available in the URL window:
Copy the value of the code (i.e. code=[authorization_code]) into a text editor, and then URL decode any characters that are URL encoded. In my experience, this is typically two %3D characters at the end of the code, which equates to two equal signs, but I make no claim as to the standard.
Use the Authorization Code to get the Access Token via cURL
Note: If you are attempting to do this in Production, then use 'login' instead of 'test' in the URL.
curl --request POST 'https://test.salesforce.com/services/oauth2/token' --data 'client_id=[Consumer Key from Connected App]' --data 'client_secret=[Consumer Secret from Connected App]' --data 'code=[Authorization Code from Previous Call]' --data 'redirect_uri=https://localhost' --data 'grant_type=authorization_code'
This will return the following response (in non-pretty print format):
{"access_token":"[access_token]","signature":"[signature_redacted]","scope":"api","instance_url":"https://[instance].my.salesforce.com","id":"https://test.salesforce.com/id/[id_redacted]/[id_redacted]","token_type":"Bearer","issued_at":"1588342208615"}
Use the access_token to make API calls:
Note: The following example is highly specific (e.g. POST, json, etc), so adjust accordingly.
curl --request POST '[REST API URI]' --header 'Authorization: Bearer [access_token]' --header 'Content-Type: application/json' --data '{"key_1" : "value_1","key_2" : "value_2"}'
Special Note: The examples worked using Git Bash on Windows, and may need to be modified to work in the Windows Command Window (i.e. you may need to enclose arguments in double quotes and escape double quotes in JSON, etc). Just beware of this nuance.
No comments:
Post a Comment