Salesforce Node.js Canvas Signed Request


In this blog, I am going to explain how to set up salesforce canvas signed the request with node js. Signed Request is default authentication for canvas app. The signed request authorization flow varies depending on whether the canvas app’s Permitted Users field is set to “Admin approved users are pre-authorized” or “All users may self-authorize”. The signed request containing the consumer key, access token, and other contextual information is provided to the canvas app if the administrator has allowed access to the canvas app for the user or if the user has approved the canvas app via the approve/deny OAuth flow

Setup Connected App
First, we are going to create a connected app to obtain the consumer secret key which we will be used in the signed request.

  1. In Salesforce, from Setup, enter Apps in the Quick Find box, then select Apps.
  2.  In the Connected Apps related list, click New.
  3. In the Connected App Name field, enter NodeJsSignedRequest.
  4. In the Contact Email field, enter your email address.
  5.  In the API (Enable OAuth Settings) section, select the Enable OAuth Settings field.
  6. In the Callback URL field, enter https://localhost:8443/sdk/callback.html.
  7. In the Selected OAuth Scopes field, select Full Access.
  8. In the Canvas App Settings section, select Canvas.
  9. In the Canvas App URL field, enter https://localhost:8443/
  10. In the Access Method field, select the Signed Request (Post).
  11. In the Locations field, select Chatter Tab and save it.

On the detail page for the canvas app, next to the Consumer Secret field, click the link Click to reveal. The consumer secret is used in the app to authenticate. We will configure the this later in the Heroku apps.

Configure Who Can Access the Canvas App

Now you need to configure the canvas app for the user access

  1. go to “NodeJSSignedRequest” managing connected apps and click on manage and edit policies
  2.  In the Permitted Users field, select “Admin approved users are pre-authorized.” and then save it 
    3. In the Profiles related list, click Manage Profiles.
    4. Select the System Administrator profile and click Save.

Time to Code

1 .create a package.json file as shown below

  "name": "signedrequest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "express": "~4.8.1",
    "body-parser": "~1.2.2",
    "request": "~2.36.0",
    "ejs": "~1.0.0",
    "crypto-js": "^3.1.6"
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  "author": "",
  "license": "ISC"

2.create index.js file as shown below

var express = require('express'),
  bodyParser = require('body-parser'),
  path = require('path'),
  CryptoJS = require("crypto-js");
var app = express();
var consumerSecret = process.env.CANVAS_CONSUMER_SECRET;

app.use(express.static(path.join(__dirname, 'views')));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ entended: true }));
app.get('/', function (req, res) {
});'/', function (req, res) {
  var signed_req = req.body.signed_request;
  var hashedContext = signed_req.split('.')[0];
  var context = signed_req.split('.')[1];
  var hash = CryptoJS.HmacSHA256(context, consumerSecret);
  var b64Hash = CryptoJS.enc.Base64.stringify(hash);
  if (hashedContext === b64Hash) {
    res.render('index', { req: req.body, res: });
 } else {
    res.send("authentication failed");
var port = process.env.PORT || 9000;
console.log('Listening on port ' + port);

3. create the index.ejs view inside the “views” folder.

<!DOCTYPE html>
<html lang="en">

    <meta charset="utf-8">

    <%- JSON.stringify(req) %>


4. Create Profile to host it to Heroku

web: node index.js

5. Run the following commands from the terminal.

heroku login 
git init
git add .
git commit -m "Commit"
heroku create 
git push heroku master

6. Set the environmental variable to Heroku app. we are going to set the environmental variable with consumer secret which we got in the connected app.

heroku config:set CANVAS_CONSUMER_SECRET=2781208380818866866

7. Now you will see Heroku app URL some think like .

8. Go to the connected app and edit and replace OAuth callback URL and canvas app URL with Heroku app URL.

9. Now if you can go to chatter page you see the canvas app is returning the response with SignedRequest.

What Signed Request Contains?

The signed request is a string of the following elements concatenated

  • The canvas app consumer secret encrypted with HMAC SHA–256 algorithm
  • A period (“.”)
  • The context and authorization token JSON encoded in Base64

When using a signed request, Salesforce delivers the user context and authentication information to your canvas app URL. To ensure that the signed request is valid, you must verify that the signed request was signed using your specific canvas app consumer secret as explained below.

  1. Receive the POST message that contains the initial signed request from Salesforce.
  2. Split the signed request in the first period. The result is two strings: the hashed Based64 context signed with the consumer secret and the Base64 encoded context itself.
  3. Use the HMAC SHA-256 algorithm to hash the Base64 encoded context and sign it using your consumer secret.
  4. Base64 encode the string created in point 3.
  5. Compare the Base64 encoded string with the hashed Base64 context signed with the consumer secret you received in point 2.




Salesforce Username and Password OAuth flow


In this blog, I am going to explain how to setup and test OAuth username and password flow also called as  Resource Owner Password Credentials Flow.With this type of authorization, the credentials (and thus the password) are sent to the client and then to the authorization server along with the client and client secret. In this flow, the user’s credentials are used by the application to request an access token which you case use to access the data on behalf of the user.

Use Case

  • If you would like to access another salesforce instance data by using rest API
  • Resource Owner has a trust relationship with the client like if you are making calls from internal or secured on-premise application.

Create a Connected App

  1.  Navigate to App Setup > Create > Apps > Connected Apps > New
  2.  Enter  Connected App Name, API Name, Contact Email
  3.  In the API (Enable OAuth Settings) Section click the Enable OAuth Settings checkbox.
  4.  Enter an arbitrary Callback URL, such as
  5. For Selected OAuth Scopes as full
  6.  Click the Save button.
  7. Navigate to Administration Setup > Manage Apps > Connected Apps
  8. Click on the link of the name of the Connected App created above.
  9. Click on the Edit button
  10. In the Permitted Users drop-down, select Admin approved users are pre-authorized and click OK on the popup.
  11. For the IP Restrictions dropdown, choose to Relax IP restrictions, or choose another option based up requirements.
  12. For the Require Users to Log in radio button, select Refresh Token is valid until revoked.
  13. Click Save
  14. On the Connected App page, in the Profiles section click on the Manage Profiles button and Add the profile

Requesting an Access Token

The client token request should be sent in an HTTP POST to the token endpoint with the following parameters.

  • grant_type— Value must be the password for this flow
  • client_id— Consumer key from the connected app definition
  • client_secret—  Consumer secret from the connected app definition.
  • username—User’s username
  • password—User’s password
  • format – Optional URLENCODED, JSON ,XML are supported

Here’s an example of the body of the out-of-band POST.


Handling the Response

 After the request is verified, Salesforce sends a response to the client. The following parameters are in the body of the response
 Here is the sample response
  • access_token—Salesforce session ID that can be used with the web services API.
  • token_type—Value is Bearer for all responses that include an access token.
  • instance_url—A URL indicating the instance of the user’s Org. For example
  • id—Identity URL that can be used to both identify the user and query for more information about the user.
  • signature—Base64-encoded HMAC-SHA256 signature signed with the consumer’s private key containing the concatenated ID and issued_at. Use to verify that the identity URL hasn’t changed since the server sent it.
  • issued_at—When the signature was created.

Let’s test it

now the below code is used to send the OAuth details to salesforce endpoint URL which is going to return access token. you can use access token for subsequence calls.

 String endpoint='';
        String username = '*****';
        String password = '**';
        String ClientId= '***';
        String ClientSecret = '**'; 
        Httprequest req = new HttpRequest();    
        req.setBody('grant_type=password' + 
                    '&client_id=' + ClientId + 
                    '&client_secret=' + ClientSecret + 
                    '&username=' + username +
                    '&password=' + password
        Http http = new Http();
        HttpResponse res= http.send(req);                
        JSONParser parser = JSON.createParser(res.getBody());
        String accessToken ;        
        while (parser.nextToken() != null) {
            if ((parser.getCurrentToken() == JSONToken.FIELD_NAME)) {
                String fieldName = parser.getText();
                if (fieldName == 'access_token') {
                    accessToken = parser.getText();

You can use the access token to authenticate sub sequence calls. you can use access token as similar to session id as shown below.

 HttpRequest request=new HttpRequest();
        request.setHeader('Authorization','Bearer '+accessToken);
        Http hp=new Http();
        HttpResponse response=new HttpResponse();



Salesforce OAuth Explained

Introduction to OAuth:-

In this blog, I am going to explain about OAuth and different types of OAuth flows along with the examples. OAuth is delegated protocol that allows a third-party application to grant limited access to HTTP server on behalf of a resource owner or by allowing the third-party application to obtain access on its own behalf. Access is requested by a client, it can be a website or a mobile application etc.Let’s assume that you want to access the Salesforce API from some third-party web application that was hosted on your own server or assume on Heroku. Since you want to retrieve data from a resource server using OAuth2, you have to register as a client of the authorization server. Before digging more into Salesforce OAuth let’s take into some basic terminology like OAuth roles and tokens, scopes.

OAuth Roles: –

Resource Owner:  Normally resource owner is user who authorizes an application to access their account
Resource Server: server hosting protected data (Salesforce)
Client: application requesting access to a resource server (it can be a website, a Javascript application or a mobile application).
Authorization Server: server( Salesforce) issuing access token to the client. This token will be used for the client to request the resource server. This server can be the same as the authorization server.
Client ID and Client Secret: – Once your application is registered with Server, the service will issue “client credentials” in the form of a client identifier and a client secret. The Client ID is a publicly exposed string that is used by the service API to identify the application and is also used to build authorization URLs that are presented to users. The Client Secret is used to authenticate the identity of the application to the service API when the application requests to access a user’s account and must be kept private between the application and the API.


Tokens are random strings generated by the authorization server and are issued when the client requests them.OAuth Supports 2 types of token:
                Authorization Code: An authorization code is a short-lived token created by the authorization server and passed to the client application via the browser. The client application sends the authorization code to the authorization server to obtain an access token and, optionally, a refresh token.
                 Access Token: this is the most important because it allows the user data from being accessed by a third-party application. This token is sent by the client as a parameter or as a header in the request to the resource server. It has a limited lifetime, which is defined by the authorization server.
                Refresh Token: this token is issued with the access token but unlike the latter, it is not sent in each request from the client to the resource server. It merely serves to be sent to the authorization server for renewing the access token when it has expired.
              ID Token: OpenID Connect defines the ID token, a signed data structure that contains authenticated user attributes including a unique identifier for the end-user, the time at which the token was issued, and an identifier for the client application that requested the token.

Understanding OAuth Endpoints

OAuth endpoints are the URLs you use to make OAuth authentication requests to Salesforce. You need to use the correct Salesforce OAuth endpoint when issuing authentication requests in your application. The primary OAuth endpoints are:

Replace if you are validating in Salesforce sandbox.


OAuth 2.0 Grants 

The OAuth 2.0 specification is a flexible authorization framework that describes a number of grants (“methods”) for a client application to acquire an access token (which represents a user’s permission for the client to access their data) which can be used to authenticate a request to an API endpoint.OAuth is having these below grant types 

  • Authorization code grant
  • Implicit grant
  • Resource owner credentials grant
  • Client credentials grant
  • Refresh token grant

OAuth Authentication flows:-

Salesforce supports six authentication flows. you can choose any one of these flow based on the where you are hosting your application.

  • Web Server –  This is the OAuth 2.0 authorization code grant type. The web server authentication flow is used by apps that are hosted on a secure server. A critical aspect of the web server flow is that the server must be able to protect the consumer secret. You can use code challenge and verifier values in the flow to prevent authorization code interception.In this flow, the client application requests the authorization server to redirect the user to another web server or resource that authorizes the user and sends the application an authorization code. The application uses the authorization code to request an access token.
  • User-Agent – users can authorize your desktop or mobile application to access their data, leveraging an external or embedded browser (or user-agent) for authentication – the OAuth 2.0 implicit grant type.used by applications that cannot securely store the consumer secret. The user-agent authentication flow is used by client apps (consumers) that reside on the user’s device or computer. It’s also used by client apps running in a browser using a scripting language such as JavaScript. These apps can protect per-user secrets. But, because the apps are widely distributed, the client secret can’t be confidential.

  • JWT Bearer Token Flow – your app can re-use an existing authorization by supplying a signed JSON Web Token (JWT) as described in JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants.
  • SAML Bearer Assertion Flow – your app can also re-use an existing authorization by supplying a signed SAML 2.0Assertion, as specified in the SAML 2.0 Profile for OAuth 2.0 Client Authentication and Authorization Grants.
  • SAML Assertion Flow – your app can federate with the API using a SAML Assertion, in much the same way as you would configure Federation with Salesforce for Web single sign-on.
  • Username and Password – your application can authenticate directly to using an ‘API user’s credentials – the OAuth 2.0 resource owner password credentials grant type.where the application has direct access to user credentials. Note that you should avoid the username and password flow wherever possible, since the other flows free your application from having to manage, store and protect user credentials, but be careful – if you use the web server profile you must store the client secret securely.


The scope is a parameter used to limit the rights of the access token. Salesforce Support these scopes namely API, Chatter_api, custom_permissions, full, id, opened, refresh_token, visualforce, the web

‘Selected OAuth Scopes’ control the types of resources that the client application can access in a Salesforce organization. Supported values are:

  • api – Allows access to the current, logged-in user’s account over the APIs, such as the REST API or Bulk API. This value also includes chatter_api, which allows access to Chatter REST API resources.
  • chatter_api – Allows access to only the Chatter REST API resources.
  • full – Allows access to all data accessible by the current, logged-in user. full does not return a refresh token. You must explicitly request the refresh_token scope to get a refresh token.
  • id – Allows access to the Identity Service. You can request profileemailaddress, or phone, individually to get the same result as using id; they are all synonymous.
  • openid – Allows access to the current, logged in user’s unique identifier for OpenID Connect apps. The openid scope can be used in the user-agent flow and the web server flow to get back a signed ID token conforming to the OpenID Connect specifications in addition to the access token.
  • refresh_token – Allows a refresh token to be returned if you are eligible to receive one, and is synonymous with requesting offline_access.
  • visualforce – Allows access to Visualforce pages.
  • web – Allows the ability to use the access_token on the Web. This also includes visualforce, allowing access to Visualforce pages.

Just to understand the OAuth grant types and scopes first we need to create a connected app in Salesforce. Go to Setup -> Create -> Apps -> Create a new Connected App in Salesforce as shown below

  1. From Setup, go to Apps and click New in the Connected Apps 
  2. Enter the name of your application.
  3. Enter the contact email information
  4. Select Enable OAuth Settings.
  5. Enter a Callback URL
  6. Add all supported OAuth scopes to Selected OAuth Scopes.
  7. Enter a URL for Info URL
  8. Click Save. The Consumer Key is created and displayed, and the Consumer Secret is created (click the link to reveal it).

OAuth 1

Click on Save
Click Continue  to obtain the Consumer secret and consumer key

OAuth 2

Now Salesforce Authorization server response with Consumer secret and consumer key which you are going to use in your server-side application.For each registered application, you’ll need to store the public client_id and the private client_secret which you can use to obtain the access token and refresh tokens.Based on how you wanted to obtain the access and refresh token, OAuth will support different types of grants and flows.


Salesforce Async SOQL

In this blog, I am going to explain the salesforce Async SOQL. Async SOQL you can use for the long-running data-set which will execute on the data set then the data-set result will be passed to object like a pipeline. Async SOQL is a method for running SOQL queries in the background over Salesforce entity data, including subjects, BigObjects, and external objects (accessed via Lightning Connect). Async SOQL is implemented in the form of a Restful API that enables you to run queries in the familiar syntax of the SOQL language. You can run multiple queries in the background, and monitor their completion status.The results of each query are deposited into an object you specify, which can be a sObject or BigObject. As a result, you can subset, join, and create more complex queries that are not subject to timeout limits. For example, let’s say that you want to analyze the years and years of opportunity history data. The results could help you identify which current and future opportunities are more likely to close and give you a better picture of your forecast by reducing your billion rows of data into the manageable size.

Sort of  Pipeline

Async SOQL is acting like a sort of data Pipeline. the pipeline is a set of data processing elements connected in series, where the output of one element is the input of the next one. below image shows the differences.

Async SOQL Versus SOQL
Use standard SOQL when:
• You want to display the results in the UI without having the user wait for results.
• You want results returned immediately for manipulation within a block of Apex code.
• You know that the query will return a small amount of data.
Use Async SOQL when:
• You are querying against millions of records.
• You want to ensure that your query completes.
• You do not need to do aggregate queries or filtering outside of the index

Run Async SOQL

To Run Async Queries you need to make the POST REST API Call to /services/data/v41.0/async-queries the endpoint with JSON encoded list of the request body.

"query": "SELECT  Amount ,ClosedDate ,StageName  FROM Opportunity ",
"operation": "insert",
"targetObject": "Sales_OrderBO__b",
"targetFieldMap": {"Amount ":"Actual_Cost__c",
"StageName ":"Saleschannel__c ",

The response of an Async SOQL query displays the jobID,  SOQL command, details of the field mapping, and the target object. It also displays the query status, which can have one of three values: Running, Complete, or can use Job Id to track the status of your Async SOQL.

Few Standard Use Cases from Salesforce docs 

1.Data Archiving
To archive records for long-term retention in a BigObject, Async SOQL can easily move any number of records from a sObject into a BigObject. The data archive process can be achieved via the following programmatic flow.
1. Define source sObject records.
2. Define target BigObject(s).
3. Define sObject to BigObject field mappings.
4. Use Async SOQL to copy records from sObject to BigObject storage.
5. Conceive and orchestrate the delete process driven by the parent IDs via APIs.

Create a new job by sending a POST request to the following URI. The request body identifies the type of object to be queried, the target object, and supporting mapping. This example archives all cases whose status is closed.

Example request body

"jobId": "08PB000000003NS",
"query": "SELECT id, CaseNumber, ClosedDate, ContactId, CreatedById, Description
FROM Case WHERE Status = 'Closed'",
"status": "Complete",
"targetFieldMap": {"id": "originalCaseId__c",
"CaseNumber": "caseNumber__c",
"ClosedDate": "closedDate__c",
"ContactId": "contactId__c",
"CreatedById": "createdById__c",
"Description": "Description__c"
"targetObject": "ArchivedClosedCases__b"

Example response body

"jobId": "08PB000000003NS",
"query": "SELECT id, CaseNumber, ClosedDate, ContactId, CreatedById, Description
FROM Case WHERE Status = 'Closed'",
"status": "Complete",
"targetFieldMap": {"id": "originalCaseId__c",
"CaseNumber": "caseNumber__c",
"ClosedDate": "closedDate__c",
"ContactId": "contactId__c",
"CreatedById": "createdById__c",
"Description": "Description__c"
"targetObject": "ArchivedClosedCases__b"


2. Customer 360° and Filtering

in this use case, customers load a variety of customer engagement data from external sources into Salesforce BigObjects and then process the data to enrich customer profiles in Salesforce. The idea is to store customer transactions and interactions such as point-of-sale data, orders, and line items in BigObjects, then process and correlate that data with your core CRM data.  In the following example, we want to analyze the customer data stored in the Rider record of a car-sharing service. The source BigObject, Rider_Record_b, has a lookup relationship with the Contact object, allowing for an enriched view of the contact’s car riding history

Example request body

"query": "SELECT End_Location_Lat__c, End_Location_Lon__c, End_Time__c,
Start_Location_Lat__c, Start_Location_Lon__c, Start_Time__c,
Uber_Type__c, Rider__r.FirstName, Rider__r.LastName,
FROM Rider_Record__b WHERE Star_Rating__c = '5'",
"targetObject": "Rider_Reduced__b",
"targetFieldMap": {"End_Location_Lat__c":"End_Lat__c",
"Start_Location_Lat__c": "Start_Lat__c",
"Start_Location_Lon__c": "Start_Long__c",
"End_Time__c": "End_Time__c",
"Start_Time__c": "Start_Time__c",
"Uber_Type__c": "Uber_Type__c",
"Rider__r.FirstName": "First_Name__c",
"Rider__r.LastName": "Last_Name__c",
"Rider__r.Email": "Rider_Email__c"

Example response body

"jobId": "08PB000000000NA",
"query": "SELECT End_Location_Lat__c, End_Location_Lon__c, End_Time__c,
Start_Location_Lat__c, Start_Location_Lon__c, Start_Time__c,
Uber_Type__c, Rider__r.FirstName, Rider__r.LastName,
FROM Rider_Record__b WHERE Star_Rating__c = '5'",
"status": "Complete",
"targetFieldMap": {"End_Location_Lat__c":"End_Lat__c",
"Start_Location_Lat__c": "Start_Lat__c",
"Start_Location_Lon__c": "Start_Long__c",
"End_Time__c": "End_Time__c",
"Start_Time__c": "Start_Time__c",
"Uber_Type__c": "Uber_Type__c",
"Rider__r.FirstName": "First_Name__c",
"Rider__r.LastName": "Last_Name__c",
"Rider__r.Email": "Rider_Email__c"
"targetObject": "Rider_Reduced__b"


a.Field Audit Trail

You can use Async SOQL to query archived fields, stored in the FieldHistoryArchive object. You can use the WHERE clause to filter the query by specifying comparison expressions for the FieldHistoryType, ParentId, and CreatedDate fields,
as long as you specify them in that order.

Example Request body

"query": "SELECT ParentId, FieldHistoryType, Field, Id, NewValue, OldValue
FROM FieldHistoryArchive WHERE FieldHistoryType = ‘Account’
AND CreatedDate > LAST_MONTH”,
"targetObject": "ArchivedAccounts__b",
"targetFieldMap": {"ParentId": "ParentId__c",
"FieldHistoryType": "FieldHistoryType__c",
"Field": "Field__c",
"Id": "Id__c",
"NewValue": "NewValue__c",
"OldValue": "OldValue__c"

Example Response 


"jobId": "07PB000000006PN",
"query": "SELECT ParentId, FieldHistoryType, Field, Id, NewValue, OldValue
FROM FieldHistoryArchive WHERE FieldHistoryType = ‘Account’
AND CreatedDate > LAST_MONTH”,
"status": "Complete",
"targetFieldMap": {"ParentId": "ParentId__c",
Async SOQL Use Cases
"FieldHistoryType": "FieldHistoryType__c",
"Field": "Field__c",
"Id": "Id__c",
"NewValue": "NewValue__c",
"OldValue": "OldValue__c"
"targetObject": "ArchivedAccounts__b"


b.Event Monitoring

Login Forensics and Data Leakage Detection, both currently in pilot, enable you to track who is accessing confidential and sensitive data in your Salesforce Org. You can view information about individual events or track trends in events to swiftly identify unusual behavior and safeguard your company’s data. This is particularly useful for compliance with regulatory and audit requirements.For example, let’s say you want to know everyone who viewed the contact record of your company’s CEO. The key to this query is the CEO’s contact record Id. Let’s say the CEO’s name is Jane Doe, and her Id is 003D000000QYVZ5

Example Request Body

"query": "SELECT Soql, SourceIp, Username, EventTime FROM ApiEvent
WHERE RecordInfo Like '%003D000000QYVZ5%'",
"targetObject": "QueryEvents__c",
"targetFieldMap": {"Soql":"QueryString__c","SourceIp":"IPAddress__c",
"Username":"User__c", "EventTime":"EventTime__c",


Example Response 

"jobId": "05PB000000001PQ",
Async SOQL Use Cases
"query": "SELECT Soql, SourceIp, Username, EventTime
FROM ApiEvent WHERE RecordInfo Like '%003D000000QYVZ5%'",
"status": "Complete",
"targetFieldMap": {"Soql":"QueryString__c","SourceIp":"IPAddress__c",
"Username":"User__c", "EventTime":"EventTime__c",
"targetObject": "QueryEvents__c"