Day: October 19, 2017

Salesforce Node.js Canvas Signed Request

Introduction

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 Force.com 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

2.create index.js file as shown below

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

4. Create Profile to host it to Heroku

5. Run the following commands from the terminal.

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.

7. Now you will see Heroku app URL some think like https://arcane-woodland-93536.herokuapp.com/ .

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

Introduction

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 https://login.salesforce.com/services/oauth2/callback.
  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 https://yourInstance.salesforce.com/.
  • 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.

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

 

 

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:

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:
  • For authorization: https://login.salesforce.com/services/oauth2/authorize
  • For token requests: https://login.salesforce.com/services/oauth2/token
  • For revoking OAuth tokens:https://login.salesforce.com/services/oauth2/revoke

Replace test.salesforce.com 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 Force.com 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.
 

Scopes

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.

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 Failed.you 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

Example response body

 

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

Example response body

 

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

Example Response 

 

 

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

 

Example Response 

 

Salesforce Big Objects

Introduction

Salesforce Big objects let you store and manage massive amounts of data on
the Salesforce platform like storing the huge historical data.Big objects capture data for use within Force.com and are accessible via a standard set of APIs to clients and external systems. big objects are that they have been built to provide consistent performance whether there are 1 million records, 100 million, or even 1 billion records. This scale is what gives big objects their power and what defines the features that are provided.

Two Types of Big Objects 

Standard big objects — Objects defined by Salesforce and included in Salesforce products. FieldHistoryArchive is a standard big object that stores data as part of the Field Audit Trail product.
 Custom big objects— New objects that you create to store information unique to your Org.

How to Create a BigObject?

you need to define the big objects using metadata, not from the standard Salesforce UI. What we are going to do here is we are creating Sales Order Big Object to store the past historical orders. here is the metadata file you can download  Here. After downloading the zip file go to the workbench to create the big object. go to the workbench and deploy the above file as shown below

Once you can deploy the big objects  successfully, you can able to see the big objects that are created in Salesforce as shown below

Considerations

  • Big objects support only object and field permissions.
  • You must use the Metadata API to define a big object or add a field to a custom big object.Not from the UI
  •  SOQL relationship queries are based on a lookup field from a big object to a standard or custom object in the select field list
  • Big objects support custom Lightning and Visualforce components rather than standard UI elements home pages, detail pages, list views, and so on).
  •  You can create up to 100 big objects per org. The limits for big object fields are similar to the limits on custom objects and depend on your org’s license type.
  •  Big objects don’t support transactions including both big objects, standard object and custom objects.
  • At least you should have one indexed field
  • To support the scale of data in a big object, features like triggers, flows, processes, and Salesforce1, are not available.

Own Storage Space

Good to know that Salesforce big objects are come up with its own storage  space

Access Control

You can control  Read or create actions from the profile  

Insert Data into Big Object.

You can able to insert the data into the big object by using API  or  You can use a CSV file to load data into a custom big object. Here is the single record insert from the workbench. But even you can load data from CSV file.

Using Apex to insert the data 

You can create and update custom big object records in Apex using the insertImmediate method as shown below. Here in this code, I am inserting ten records for the sales order object. What we are going to do after inserting the Big Objects, we are going to create a visual force to show the custom Object and its Big object in the related list.

Using Rest API

you can insert the data into the object by using rest api post method as shown below.

You can expose the data by using the visual force page or lightning component. Here are the apex class and page.