Skip to main content

OAuth 2.0 JWT Bearer Flow for Server to Server Integration

Welcome to catchontosalesforce! 

Description :

We can authorize server to access data without interactively logging in each time and unable to share your client secrete. JWT Bearer Flow require prior approval of the client app.

JWT Bearer Flow use certificate to sign a  JWT request. it's also process by connected app. The connected app send a info to salesforce endpoint. Salesforce will validate the JWT based on a signature using a previously configured certificate and additional parameters.

Steps to achieve :
  • Create a JWT
    • Create Certificate and upload Java Key store.
    • Create Connected app with Digital Certificate.
    • Construct a JWT header and JSON Claims Set.
    • Fetch Private from certificate.
  • Request Access Token    
Create a JWT : 

We have few steps to achieve JWT.

Create Certificate and upload it in JKS : 

You can go Setup -----> Administer ----> Security Controls ----> Certificate and Key Management.

Click Create Self-Signed Certificate.

and Click Save

Once done, just export JKS file to keystore and import 
JKS file from keystore.

Create Connected app with Digital Certificate : 

You can go Setup -----> Administer ----> Create ----> Apps.

Click New in Connected App section.

You can make sure few things : 
  • Opt in to issue JSON Web Token (JWT)-based access tokens for named users must be checked.
  • Permitted Users must be Admin approved users are pre-authorized.
  • Upload your new created certificate to Digital Certificate in connected app.
  • You need to add Perform requests at any time (refresh_token, offline_access) Scope.

Construct a JWT header and JSON Claims Set : 

You can encrypted alg RSA SHA256 to sign.


JWT header : 

The format is {"alg":"RS256"} with Base64url encode.

Use : 
String base64Str = EncodingUtil.Base64Encode(Blob.valueOf('{"alg":"RS256"}'));
system.debug(base64Str);

 Base64url encode is similar to eyJhbGciOiJSUzI1NiJ9.

JSON Claims Set :

We have assign four parameter to construct  JSON Claims Set.
  • iss - Connected App Consumer Key.
  • sub - Salesforce Instance/Experience Site Username.
  • aud - Base URL of salesforce Instance/Experience Site. 
  • exp - The date and time at which the token expires.
{"iss": <Consumer Key>, 
"sub": <Username>, 
"aud": <Instance/Experience Site URL>, 
"exp": <DateandTime at UTC>}

 Base64url encode is looks like eyJpc3MiOiAiM01WRzlOdm1qZDlsY2pSbnR5T0xvbHRESS43emxjTUxDVWxEQ21MNk5fbm1DLmdPOFAwY0dGT2REN0JCTzlUeFpxSTY5TE03QVE4NHVTSG5SeWp1SiIsInN1YiI6ICJzYWxlc2ZvcmNlQGlzY2Eub3JnLnNnLnVhdCIsImF1ZCI6ICJodHRwczovL3Rlc3Quc2FsZXNmb3JjZS5jb20iLCAiZXhwIjogIjEzMzM2ODU2MjgifQ==

Fetch Private from certificate :

Just use this link to export private key from certificate.

Like this.

<Sign with Certificate Private Key> - You can use below apex method to get signature.

  • algorithmName must be RSA-SHA256
  • input must be <JWT header>.<JSON Claims Set > like eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiAiM01WRzlOdm1qZDlsY2pSbnR5T0xvbHRESS43emxjTUxDVWxEQ21MNk5fbm1DLmdPOFAwY0dGT2REN0JCTzlUeFpxSTY5TE03QVE4NHVTSG5SeWp1SiIsInN1YiI6ICJzYWxlc2ZvcmNlQGlzY2Eub3JnLnNnLnVhdCIsImF1ZCI6ICJodHRwczovL3Rlc3Quc2FsZXNmb3JjZS5jb20iLCAiZXhwIjogIjEzMzM2ODU2MjgifQ== 

Blob signature = Crypto.sign(algorithmName, input, privateKey);

String output = encodingUtil.base64Encode(signature);

output = output.replace('+', '-');

output = output.replace('/', '_');

while ( output.endsWith('=')){

output = output.subString(0,output.length()-1);

}

The output String is a Signature.

 Request Access Token : 

The Connected app post the token request to salesforce endpoint with JWT Payload.

API Details :

HTTP Request Endpoint

<Instance URL/Your Experience Site URL>+'/services/oauth2/token'


HTTP Request Method

POST

HTTP Request Header

Content-Type

application/x-www-form-urlencoded

HTTP Request Body

grant_type

urn:ietf:params:oauth:grant-type:jwt-bearer

assertion

<JWT header>.<JSON Claims Set>.<Sign with Certificate Private Key>

HTTP Response : 

{
    "access_token""xxxxxxxxxxxxxxxxxxx",
    "token_format""jwt",
    "scope""cdp_api",
    "instance_url""<Instance URL>",
    "id""",
    "token_type""Bearer"
}

You can access token to access protected salesforce data.


Thanks,
Priyananth




    Comments

    Popular posts from this blog

    HTTP POST via Lightning Flow

     I have done account sync between Salesforce (Source) to salesforce (Destination) using Lightning flow. Just visit Blog:  https://www.catchontosalesforce.com/p/http-post-via-lightning-flow.html

    Authorization Code and Credentials Flow for Private Clients

    I have created a sample javascript app with functionality of Authorization Code and Credentials Flow for Private Clients.  Just visit Blogshot:   https://www.catchontosalesforce.com/p /authorization-code-and-credentials-flow.html   Github : https://github.com/Priyananth-Salesforce/Headless-SF-Authenication--Login-Via-Javascript-App