Salesforce: OAuth 2.0 JWT Bearer Flow for Server-to-Server Integration
With this article, I am trying to complement the really nice content we already have on the Salesforce website with some insights on small details which are helpful for those who are completely new to the Salesforce world.
If you want to read first on the salesforce website, please go here and make yourself comfortable and come back here to find answers to those small questions you might have.
Why OAuth, well I have been there when one of our ex-developers integrated with Salesforce API using his own credentials(username & password) and everything was working just fine till he left and we removed his user account from the service and suddenly everything stopped working, so if you don't want to create such loophole, OAuth 2.0 is the right answer to this problem where we are not dependant on any user!
Let's start with some basic questions you might have.
- How to create an X509 certificate from scratch on a brand new windows machine?
— Install OpenSSL (https://slproweb.com/products/Win32OpenSSL.html)
— Open command prompt as an administrator
— go to Open SSL bin folder (cd C:\Program Files\OpenSSL-Win64\bin)
— execute, openssl genrsa -des3 -passout pass:MyCustomPassword -out JDemo.pass.key 2048
you can choose your own password and key name instead of JDemo
— execute, openssl rsa -passin pass:MyCustomPassword -in JDemo.pass.key -out JDemo.key
This will write RSA Key
Now we have keys, let's create a .csr file then
— execute, openssl req -new -key JDemo.key -out JDemo.csr
this command will ask you to fill in certificate details.
Now, let’s write the certificate from .csr file generated in the above step.
— execute, openssl x509 -req -sha256 -days 365 -in JDemo.csr -signkey JDemo.key -out JDemo.crt
Now you have an x509 certificate with you, you can use the same to upload on Salesforce connected app.
Private Key and Public Key
— Private Key: Open JDemo.key file in notepad and use it.
You need KeyStore Explorer to read your certificate
Install it from here.
— Public Key: Open JDemo Security Certificate(JDemo.crt) and View Public Key, Click on PEM Format.
2. How to create JWTToken programmatically?
3. How to Authorise your application
You need to authorize your newly created Connected App once to grant permissions.
replace placeholders like consumer key and domain URL as per your account and it should pop-up authentication, then it will confirm the roles you assigned and you are ready to use this connected app to generate bearer tokens.
If you have any questions, feel free to comment and I will try to answer them.
Happy Learning. Thank you!