OAuth Flow — JWT Bearer Flow

Priyank Rajvanshi
Cloudwerx
Published in
6 min readSep 27, 2022

Overview

Sometimes you want to authorize servers to access data without interactively logging in each time the servers exchange information. For these cases, you can use the OAuth 2.0 JSON Web Token (JWT) bearer flow. This flow uses a certificate to sign the JWT request and doesn’t require explicit user interaction. However, this flow does require prior approval of the client app.

With the OAuth 2.0 JWT bearer token flow, the client posts a JWT to the Salesforce OAuth token endpoint. Salesforce processes the JWT, which includes a digital signature, and issues an access token based on prior approval of the app.

Let’s go over each step of this authorization flow.

  1. Create a Certificate and private key
  2. Create a connected app in Salesforce
  3. Create a JWT
  4. Request for an access token

Create a Certificate and private key

This flow requires a digital certificate and the private key used to sign the certificate.

Please feel free to use your own private key and certificate issued by a certification authority.

Alternatively, you can use OpenSSL to create a key and a self-signed digital certificate.

Step 1 — Download OpenSSL Binary

You need to download the latest OpenSSL windows installer file. Click the below link to visit the OpenSSL download page:
https://slproweb.com/products/Win32OpenSSL.html

Step 2 — Run OpenSSL Installer

Now run the OpenSSL installer on your system. The OpenSSL required Microsoft Visual C++ to be installed on your system. If your system doesn’t have Microsoft Visual C++ installed, the installer will show your message like:

Click Yes to download and install the required Microsoft Visual C++ package on your system.

Then again run the OpenSSL installer and follow the wizard.

Step 3 — Setup Environment Variables

Now set the environment variables to function OpenSSL properly on your system. You are required to set OPENSSL_CONF and Path environment variables.

Set Variables Permanently — You can also set the OPENSSL_CONF and Path environment variables in the system permanently. To set the environment variable follow:

Press Windows + R keys together to open the run window, Then type “sysdm.cpl” in the Run dialog box and hit Enter. Alternatively, you can open Command Prompt and type the same command to open System Properties

Go to “Advanced” tab and click on “Environment variables“.

Set OPENSSL_CONF Variable:

Set Path Variable:

Generate private key and cert

To validate that you are who you say you are, this process needs you to generate an x509 certificate and key. Your JWT requests will be signed with this key and validate that you’re supposed to be able login as the user.

Open the command prompt and hit the below command in the terminal.

openssl req -x509 -sha256 -nodes -days 36500 -newkey rsa:2048 -keyout salesforce.key -out salesforce.crt

Once you will execute above command it will ask you some question and information

  • Country Name: Provide any value for example IN
  • State or province Name [Some-State]: UP
  • Locality Name( eg. city)[] : Greater Noida
  • Organization Name (eg. company) : CWX
  • Organization Unit Name : CWX
  • Comman Name [] : You can keep it blank or your name
  • Email Address [] : keep your email address

it will create two files in the local system.

Create connected app in Salesforce

  1. Login to salesforce.
  2. Go to setup area (gear in the nav in the top right)
  3. In the side nav, go to Apps > App Manager
  4. Click New Connect App
  5. In the Basic Information section, populate the required fields. The values are for book keeping only and are not part of using the API.
  6. In the API (Enable OAuth Settings) section:
  7. Check Enable OAuth Settings
  8. Callback URL is unused in the JWT flow but a value is required nonetheless. Use “http://localhost/" or some other dummy host.
  9. Check Use digital signatures. Upload the salesforce.crt that was generated earlier.
  10. For Selected OAuth Scopes, add Access and manage your data (api) and Perform requests on your behalf at any time (refresh_token, offline_access)
  11. Click Save. If there are any errors, you have to re-upload salesforce.crt
  12. On the resulting app page, click Manage.
  13. Click Edit Policies.
  14. In the OAuth policies section, change Permitted Users to Admin approved users are pre-authorized.
  15. Click Save.
  16. Back on the app page again, in the Profiles section, click Manage Profiles.
  17. On the Application Profile Assignment page, assign the user profiles that will have access to this app.
  18. ✨ NOTE : ✨ The OAuth scopes are important. Make sure you add “Perform requests at any time (refresh_token, offline_access)” in the OAuth scopes.

Pre-Approve the connected app with the User-Agent OAuth Flow

One way to pre-approve the connected is by using another simple OAuth Flow. We will use the User-Agent OAuth Flow in this example.

Copy and paste this link in the browser

https://<DOMAIN_URL>/services/oauth2/authorize?response_type=token&client_id=<consumer key>&redirect_uri=sfdc://oauth/jwt/success

once you hit this, It’ll ask you to login in the org and display below screen to allow.

Create a JWT

JWT Structure:

When we talk about JSON Web Token, it is consist of 3 parts

  1. Headers — Which contains the algorithm which will be used to sign the request {"alg":"RS256"}
  2. Payload — This contains claims information which is an object containing information about a user and additional data. Claims are set using parameters- {"iss,aud,sub,exp"}
  3. Signature — The signature consists of 3 parts and the structure is given below

example:
<headerbase64encodedurl>.<claimsbase64encodedclaims>.<signature(uses algorithm like RS 256)>

Build the JWT

JWT Header :

{
"alg": "RS256",
"typ": "JWT"
}

JWT claims :

{
"iss": "Consumer key",
"sub": "Username",
"aud": "https://<login or test>.salesforce.com",
"exp": "now + 2 minutes in Unix timestamp"
}

example:

/

Now it is time to pass verify signature details.

HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
Private Key
)

. Once all look good you will Signature Verified in bottom of the screen with JWT Token.

We can use https://jwt.io/ to replicate the above process for the verification.
To know more about JWT payload parameters, check out this site : https://www.iana.org/assignments/jwt/jwt.xml

paste the header, JWT Claim, and cory Private Key value from Salesforce.Key file, that we generated with certificate. It will generate the assertion code.

Request for an access token by POSTMAN

There are different way to test our JWT flow to get access_token. For this demo we will use POSTMAN to get access_token using JWT token which we created in last step.

End Point: https://login.salesforce.com/services/oauth2/token

Method: POST

Header Param

  • grant_type : urn:ietf:params:oauth:grant-type:jwt-bearer
  • assertion : USE JWT TOKEN created in above step using jwt.io.

Congratulation now you have access_token to execute any Salesforce API

Conclusion

We can use any programming language like Java, Python, or C# to generate the signed JWT token and access salesforce information.

More resources are available in the below links.

https://help.salesforce.com/s/articleView?id=sf.remoteaccess_oauth_jwt_flow.htm&type=5

https://www.jitendrazaa.com/blog/salesforce/using-jwt-flow-to-authenticate-nodejs-application-with-salesforce/

--

--