Sunday, December 3, 2023

How to Authenticate Salesforce using OAuth2.0

In this blog, we will see how to authenticate Salesforce by using OAuth 2.0 from MuleSoft 4.x and access some object data (Contact, Account ..etc)

OAuth 2.0 is an open protocol that authorizes secure data sharing between applications through the exchange of tokens.

The following are the main steps..
  1. In order to initiate the authorization flow, connected app to be created in Salesforce to access REST API resource on behalf of a client app(MuleSoft).
  2. Authorizing server (Salesforce) grants access tokens to the connected app.
  3. A Resource server validates this access token and approves access to the protected REST API resource.
How to create a Connected App in Salesforce:
If you've Salesforce Admin access, then you can create by following below steps. Else, you need to request Salesforce Admin to provide the same.

Login into Salesforce account..
Goto Setup> Build> Create> Apps


Click on New - to create Connected App
Specify App Name as per your business requirement.
Specify Callback URL and select OAuth Scopes and move them to Right Box and Save it.
Note: It takes around 10 min to create / update the app.


Click on Manage Consumer Details for Consumer Key and Consumer Secret and note it.
These are the confidential details being used in MuleSoft to connect it.



How to test the connectivity and access object from Postman..
Specify grant-type, client-id, client-secret, username, password under Query Params and under Headers specify content-type as "application/x-www-form-urlencoded"


Once the got the token, then invoke Salesforce API for object query.

Sample Query: 


List of records from Salesforce - contacts object.

Now, we will see how to build the same logic in Anypoint Studio.


On HTTP Request: (Do the same thing as we did in postman as shown above)
Under Headers> specify content-type ()
Query Paramets> grant-type, client-id, client-secret, username, password 
Now, we need to save the token in a variable. 
In real time, we will use Object Store to maintain the token.
Invoke Salesforce API by using token..


That's all, now invoke the flow from Postman and check the results.




Source code: OAuth-Salesforce

Thanks for reading :-)

No comments:

Post a Comment