Salesforce Auth Provide – Facebook

In this blog, I am going to explain how to configure salesforce social sign on with Facebook.


Custom Domain should be created and enabled for users.

Create a Facebook application:-

First, log into the Facebook Developer Site and create a new Facebook App. You can do this by clicking the “My Apps” menu at the top of the screen and then click on the “Add a New App” button. You should see something like the following:

Enter a “Display Name” (the name of your app), and choose a category for your app. Once you’ve done this, click the “Create App ID” button.
Next, click on Settings on the left side, and make note of the App ID and App Secret. You’ll need those later when you connect your Facebook Application to Salesforce. Click “Submit” to finish creating the new application. Your App Id and App Secret looks as shown below

Configure Facebook authentication provider in your Salesforce:-
Now we are going to configure your salesforce login by using the facebook. To do this , go to setup ->Security Controls ->Auth Providers -> New –>Select Facebook as Provider Type as shown below

Enter a Name for the provide as Facebook or you can choose your any desired name wish to have
Enter Consumer Key and Consumer secret from the App id and App Secret which you got from the facebook application.
Authorize Endpoint URL and Token Endpoint URL, User Info Endpoint URL are optional and leave it as of now.
click ‘Automatically create a registration handler template’.this is going to create a new Apex Class which will handle the user login by using facebook. If the User is not there in salesforce it’s going to create a new user or if exists it’s going to update the user
Select Execute Registration As any System admin User. Make sure user is having Manage users permission

Salesforce generated Registration handler looks as shown below. you can update the Registration handler with your own logic.
global class AutocreatedRegHandler1489086488327 implements Auth.RegistrationHandler{
global boolean canCreateUser(Auth.UserData data) {
//TODO: Check whether we want to allow creation of a user with this data
//Set<String> s = new Set<String>{‘usernamea’, ‘usernameb’, ‘usernamec’};
//if(s.contains(data.username)) {
//return true;
return false;

global User createUser(Id portalId, Auth.UserData data){
if(!canCreateUser(data)) {
//Returning null or throwing an exception fails the SSO flow
return null;
if(data.attributeMap.containsKey(‘sfdc_networkid’)) {
//We have a community id, so create a user with community access
//TODO: Get an actual account
Account a = [SELECT Id FROM account WHERE name=’Acme’];
Contact c = new Contact();
c.accountId = a.Id; =;
c.firstName = data.firstName;
c.lastName = data.lastName;

//TODO: Customize the username and profile. Also check that the username doesn’t already exist and
//possibly ensure there are enough org licenses to create a user. Must be 80 characters or less.
User u = new User();
Profile p = [SELECT Id FROM profile WHERE name=’Customer Portal User’];
u.username = data.username + ‘’; =;
u.lastName = data.lastName;
u.firstName = data.firstName;
String alias = data.username;
//Alias must be 8 characters or less
if(alias.length() > 8) {
alias = alias.substring(0, 8);
u.alias = alias;
u.languagelocalekey = UserInfo.getLocale();
u.localesidkey = UserInfo.getLocale();
u.emailEncodingKey = ‘UTF-8’;
u.timeZoneSidKey = ‘America/Los_Angeles’;
u.profileId = p.Id;
u.contactId = c.Id;
return u;
} else {
//This is not a community, so create a regular standard user
User u = new User();
Profile p = [SELECT Id FROM profile WHERE name=’Standard User’];
//TODO: Customize the username. Also check that the username doesn’t already exist and
//possibly ensure there are enough org licenses to create a user. Must be 80 characters
//or less.
u.username = data.username + ‘’; =;
u.lastName = data.lastName;
u.firstName = data.firstName;
String alias = data.username;
//Alias must be 8 characters or less
if(alias.length() > 8) {
alias = alias.substring(0, 8);
u.alias = alias;
u.languagelocalekey = UserInfo.getLocale();
u.localesidkey = UserInfo.getLocale();
u.emailEncodingKey = ‘UTF-8’;
u.timeZoneSidKey = ‘America/Los_Angeles’;
u.profileId = p.Id;
return u;

global void updateUser(Id userId, Id portalId, Auth.UserData data){
User u = new User(id=userId);
//TODO: Customize the username. Must be 80 characters or less.
//u.username = data.username + ‘’; =;
u.lastName = data.lastName;
u.firstName = data.firstName;
//String alias = data.username;
//Alias must be 8 characters or less
//if(alias.length() > 8) {
//alias = alias.substring(0, 8);
//u.alias = alias;


Map the Callback URL in Facebook

Now you have to go back the Facebook application which you created earlier, then associated your Callback URL in facebook as shown below.
Go back to your facebook application you just created in last steps. Click on Settings in left option bar. Click on Add Platform.

Select Platform as web Platform. Update the Salesforce call backURL in Site URL as shown below

Testing Application:-

You can test your application by simply pasting Test-Only Initialization URL in browser it will redirect to the facebook login page.
Adding the Facebook login to My Domain:-
To available facebook login for all the user, you must need to add it to my domain in salesforce as shown below.
Go to Setup –> Domain Management –> My Domain.
go to Authentication Configuration Click edit then Select Facebook as shown below.Save it

After adding it my domain you can able to login into salesforce by directly using your facebook from your domain login page as shown below.

Now you can able to login into salesforce by using facebook. once you select the facebook login it will redirect to the facebook for login. Up success login in facebook, you will be redirected to salesforce homepage.


Salesforce Platform encryption Setup

In this blog, I am going to explain how to setup platform encryption basic setup which includes setup your tenant secret keys, Creating an encrypted fields and files, tenant secret key life cycle.

Do we need any special permission?

Before setup the platform encryption, the user need this permission.

Manage Encryption Keys – To create a Tenant Secret keys.
View Encrypted Data – To view the encrypted data.

Generate a Tenant Secret

Platform encryption works based on the Tenant Secret and Master Secret keys. The master secret key is managed by the salesforce and rotates for every release. whereas Tenant Secret is An organization-specific secret used in conjunction with the master secret and key derivation function to generate a derived data encryption key. When an organization administrator rotates a key, a new tenant secret is generated. to generate the Tenant Secret go to Setup, enter Platform Encryption in the Quick Find box, then select Platform Encryption. Select Generate Tenant Secret as shown below . The platform encryption link is under Security Control.

As an admin, you can able to manage the tenant secret keys life cycle like archive and active and destroy as shown below. You can rotate your tenant secret key for every 24 hrs in production.

Encryption on fields and Files

With the new platform encryption, you can be able to encrypt the fields and Files.

What Standard fields are support encryption?

Salesforce support the following standard fields on Account, contact, and Case are encryption

How to encrypt the files?

in order to encrypt the files, go to setup — > Security Control — > Platform Encryption.
Under File and Field encryption check the Encrypted fields and attachment and save it

That’s it. Now you are good to enjoy the platform encryption future

How to create an encrypted field?

Now we are going to create a new custom field on contact called SSN which is encrypted .goto Setup -> Customize > Contact fields –> create a new custom some field SSN with Text data type
as shown below. Make Sure encrypted checkbox is checked. Save the field.


After contact record is created, the SSN values are encrypted as shown below

File encryption looks as shown below.

Sales force Platform Encryption API – APEX

In this blog, I am going to explain how to use the TenantSecret object in salesforce to generate the tenant secret key for Platform encryption.

We are going to build the visualforce page that used to create tenant secret key and view all the existing tenant secret key. Visualforce page looks as shown below

The Page controller is shown below

controller :-
public class TenantController {

public TenantSecret secretKey {get;set;}
public TenantController(ApexPages.StandardController controller){
this.secretKey = new TenantSecret();

public PageReference insertNewSecret(){
system.debug(‘Key’+secretKey );
insert secretKey ;
}catch(Exception e ){
ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,e.getMessage());
return null ;

public List<TenantSecret> getKeyHistory(){

return [Select Id ,
Description ,
Source ,
Type ,
from TenantSecret ];



Visual force page is shown below.

<apex:page standardController=”TenantSecret” extensions=”TenantController” docType=”html-5.0″ applyhtmltag=”true”
showheader=”true” sidebar=”false” standardstylesheets=”false”>

<apex:stylesheet value=”; />

background-color: PowderBlue!important;
background-image: none !important;
color: Black!important;
font-size:100% !important;
font-family: Candara, Calibri, Segoe, ‘Segoe UI’, Optima, Arial, sans-serif;
font-size: 14px;
font-variant: normal;
font-weight: normal;
line-height: 17px;

background-image: none !important;
color: Black!important;
font-size:100% !important;
font-family: Candara, Calibri, Segoe, ‘Segoe UI’, Optima, Arial, sans-serif;
font-size: 14px;
font-variant: normal;
font-weight: normal;
line-height: 17px;


<apex:form styleClass=”headerStyle”>
<apex:pageMessages ></apex:pageMessages>
<apex:pageBlock >
<apex:pageBlockSection columns=”3″>

<apex:inputField value=”{!secretKey.Description}” style=”width:80%;height:140%” />
<apex:inputField value=”{!secretKey.Type}” style=”width:40%;height:140%” />
<apex:commandButton value=”Save New Key” action=”{!insertNewSecret}”
style=”background:#4682b4;color:white;border-radius:7px” reRender=”existingkeys” />



<apex:pageBlock >
<apex:outputPanel id=”existingkeys”>

<table class=”table table-bordered table-inverse”>
<th class=”headerStyle”>Version </th>
<th class=”headerStyle”>status</th>
<th class=”headerStyle”>Type</th>
<th class=”headerStyle”>Description</th>
<th class=”headerStyle”>Source</th>
<apex:repeat value=”{!KeyHistory}” var=”key”>
<td class=”tdcls”>{!key.Version} </td>
<td class=”tdcls”>{!key.status}</td>
<td class=”tdcls”>{!key.Type}</td>
<td class=”tdcls”>{!key.Description}</td>
<td class=”tdcls”>{!key.Source}</td>




Github URL for the code:-

Salesforce Platform Encryption dislike vs like

Even though salesforce platform encryption is most powerful future it’s having certain limitation. I am going to walk through those limitations and possible solutions.

What fields are supported?

Salesforce Platform encryption support below data types on both standard and custom object Custom fields.

  • Email
  •  Phone
  • Text
  • Text Area
  •  Text Area (Long)
  •  URL
  •  Date
  •  Date/Time
  • Encrypted filed can’t use in custom formula fields
  • You can’t use Schema Builder to create an encrypted custom field.
  • Fields that have the Unique or External ID attributes or include these attributes on previously encrypted custom fields can’t be encrypted:
  • Fields that are used in custom formula fields
  • Fields that are used in an account contact relation
  • On a custom object, the standard Name field can’t be encrypted.

General features limitations? 

  • Criteria-based sharing rules
  • Similar opportunities searches
  • External lookup relationships
  • Skinny tables
  • Filter criteria for data management tools
  • Duplicate Management matching rules
  • These apps don’t support encrypted data. However, you can enable encryption for other apps when these apps are in use.  Connect Offline • • Heroku (but Heroku Connect does support encrypted data.) • Marketing Cloud (but Marketing Cloud Connect does support encrypted data.) • Pardot (but Pardot Connect supports encrypted contact email addresses if your Pardot org allows multiple prospects with the same email address.) • Process Builder • Salesforce Mobile Classic • Salesforce IQ • Social Customer Service • Steelbrick • Thunder • Visual Workflow • Wave


Encrypted fields can’t be used with the following SOQL and SOSL clauses and functions

– Aggregate functions such as MAX(), MIN(), and COUNT_DISTINCT()

– WHERE clause

–  GROUP BY clause

–  ORDER BY clause

We can use below small hints to overcome those limitations.

Hint 1: – Aggregate Result 

 In order to calculate aggregate data on encrypted field use apex code.

Hint 2: – Use SOSL instead of SOQL where conditions 

List<Account> acc= [Select Id ,Name From Contact Where Text__c= ‘123’];

The above query will fail at runtime if this is dynamic SOQL  with invalid strings return an INVALID_FIELD error instead of the expected MALFORMED_QUERY.   However, the Query can be replaced with the following SOSL statement

List<List<SObject> > acc= [FIND ‘123’ IN ALL FIELDS Returning Account(Id, Name, Text__c]

Hint 3: – ORDER BY clause

Instead of using order by clause, you can use custom apex sorting.

Hint 4: – Formula fields. 

you can use Workflows and Apex triggers to calculate the data instead of formulas on encrypted fields.

Platform Encryption with Salesforce

In this blog, I am going to explain the platform encryption and its architecture.
Introduction : 

It is common practice today to encrypt data Prevent from the unauthorized access. Salesforce Platform encryptions are allowed to today to encrypt data at rest, that is, data stored on servers with the salesforce platform encryption.  Data stored in many standard and custom fields and in files and attachments is encrypted using an advanced HSM-based key derivation system, so it is protected even when other lines of defense have been compromised.Your data encryption key is never saved or shared across organizations. Instead, it is derived on demand from a master secret and your organization-specific tenant secret, and cached on an application server.

Benefits of Encrypting Data at Rest

First and foremost, encrypting data at rest protects the organization from the physical theft of the file system storage devices (which is why end-user mobile devices from laptops to cell phones should always be encrypted). While this might sound unlikely, the physical disk devices are only as secure as the data center where they are located. Encrypting data at rest can protect the organization from unauthorized access to data when computer hardware is sent for repair or discarded.

What you can encrypt?

Salesforce platform Encryption allows you to encrypt fields, files, and attachments and Custom field as shown in this image.

Which User Permissions Does Shield Platform Encryption Require?

Assign permissions to your users according to their roles regarding encryption. Some users need the “View Encrypted Data” permission, while some need other combinations of permissions to select data for encryption or work with encryption keys. You can enable these permissions just like you would any other user permission.

How Platform Encryption Works

Shield Platform Encryption relies on a unique tenant secret that you control and a master secret that’s maintained by Salesforce. We combine these secrets to create your unique data encryption key. We use that key to encrypt data that your users put into Salesforce and to decrypt data when your authorized users need it. Encrypting files, fields, and attachments has no effect on your organization’s storage limits.

When users submit data, the application server looks for the org-specific data encryption key in its cache. If it isn’t there, the application server gets the encrypted tenant secret from the database and asks the key derivation server to derive the key. The encryption service then encrypts the data on the application server.

Take the time to identify the most likely threats to your organization. This will help you distinguish data that needs encryption from data that doesn’t so that you can encrypt only what you need to. Make sure your tenant secret and keys are backed up, and be careful who you allow managing your secrets and keys.

Before data is encrypted, a Salesforce administrator must enable encryption and generate a tenant secret. For each field, file, and attachment on which encryption is enabled, the corresponding metadata in the UDD is updated to reflect the new encryption setting. Users must have the “View Encrypted Data” permission to view encrypted field data.

  1. When a Salesforce user saves encrypted data, the runtime engine determines from metadata whether the field, file, or attachment should be encrypted before storing it in the database.
  2. If so, the encryption service checks for the matching data encryption key in cached memory.
  3. The encryption service determines if the key exists. a. If so, the encryption service retrieves the key. b. Otherwise, the service sends a derivation request to a key derivation server and returns it to the encryption service running on the App Cloud.
  4. After retrieving or deriving the key, the encryption service generates a random initialization vector (IV) and encrypts the data using JCE’s AES-256 implementation.
  5. The ciphertext is saved in the database or file storage. The IV and corresponding ID of the tenant secret used to derive the data encryption key are saved in the database.

Salesforce Named Credentials

In this blog, i am going to explain what Named Credentials. Named Credentials were introduced by Salesforce in the spring ’15 release. You can exchange secure authentication in REST API number of ways like OAuth, secure HTTP headers, other ways. Now we are going to see how named Credentials makes the differences.

Before Named Credentials?

If you think before named creations how we are managing the rest API authentication and endpoint URL  in different ways like Custom settings, Custom labels or some other options in Salesforce. Most importantly every time when you add or change you need to add it to remote site settings which are little cumbersome.If you use named credentials, you store the user credentials in the named credential itself with just clicks and configuration. It’s easy to maintain if you have to switch different creation in different org.

What is Named Credentials?

As per the document “A named credential specifies the URL of a callout endpoint and its required authentication parameters in one definition. To simplify the setup of authenticated callout, specify a named credential as the callout endpoint. If you instead specify a URL as the callout endpoint, you must register that URL in your org’s remote site settings and handle the authentication yourself”

In nutshell 

Named credentials allow you to store a URL and secret together which in turn allows Salesforce to manage all the authentication for Apex callouts that specify this named credentials

What are the benefits?

  •   Specifies the URL of a callouts endpoint and its authentication in one place
  •  No need to handle  Remote site settings of the callout URL
  •   Supports two types of authentication protocols for now: Basic Authentication(Password authentication) or OAuth.
  •  Can be configured easily if Authentication needs to be done in User Context or Admin Context

Basic HTTP Authentication 

Now lets understating how the basic HTTP Callout authentication will be handled with out using named credentials . Here we are going to use simple apex HTTP Request Class to handler the callouts as show below

HttpRequest req = new HttpRequest();
String username = ‘username’;
String password = ‘password’;
Blob headerValue = Blob.valueOf(username + ‘:’ + password);
String authorizationHeader = ‘BASIC ‘ + EncodingUtil.base64Encode(headerValue);
req.setHeader(‘Authorization’, authorizationHeader);
Http http = new Http();
HttpResponse res = http.send(req);
System.debug(‘====> result ==>’res.getBody());

even though above logic is not too complicated to handle, sensitive information like password and username got exposed. The second challenge is you need to maintain the remote site settings.

Authentication  with Named Credentials 

Now let’s see how the named Credentials make the difference in authentication  First define a Named Credential with the following values as shown below image   . to define named credentials Setup -> Security Controls ->  Named Credentials and create a new named credential.

Now you can invoke the named credentials in apex code as shown below.Apex code simply you have to pass the named credentials name followed by “callout:”

HttpRequest req = new HttpRequest();
Http http = new Http();
HTTPResponse res = http.send(req);
return res.getBody();

Limitations ?
primary named credentials was designed to implement more secure rest callout authentication. even though here are few limitations of named credentials

  • Named credentials only support HTTP Callouts and basic or OAuth 2.0 authentication. They are not an option for storing SOAP callout authentication secrets, encryption keys, or secrets for more complex authentication schemes
  • Named credentials are not currently available for packaging
  • Users with Modify All Data can update the URL

Salesforce Identity Provider for EchoSign

Introduction :- 
In this blog post, I am going to explain step by step to setup the salesforce identity provider with EchoSign. Setting up echo sign Identity with salesforce is having mainly three stages namely configuring Salesforce identity provider, configure EchoSign, create connected apps 
Prerequisites :-
1.Enable My Domain in Salesforce 

2. Start you free tail
Step1: -Enable  Salesforce Identity Provider 

1. Navigate to Setup | Administration Setup | Security Controls | Identity Provider. You should see Identity Provider setup. Click on “Enabled Identity Provider

 2. (Optionally) change the self-signed certificate to a production certificate issued by a certificate authority.This certificate is used to sign SAML assertions


3.Click on Save.As shown below Click on the Download Certificate button to download the certificate. This certificate is used to setup service providers. 


4 . Salesforce Identity Provider exposes the following endpoints. You would need these when configuring SAML at the service provider. (replace your domain with your MyDomain value) (replace your domain with your MyDomain value)

Step 2: Configure EchoSign 

  1. Sign in to your EchoSign account.
  2. Click on Account | Account Settings
  3. Click on SAML Settings tab under Account Settings.In the right side, you will see an option for SAML Mode, select SAML Allowed mode if you want users to sign in to EchoSign account using SAML as well as EchoSign credentials. Else select SAML Mandatory mode to sign in using SAML only.

4.A dedicated Hostname is required to enable SAML. If you already have dedicated hostname then this option will not be there. Otherwise, enter your hostname.

5.Under User Creation, check if you would like users to be provisioned into EchoSign when they sign in without an account.

6. Under Login Page Customization, you can enter Single Sign on Login message. It will be shown when you go for SP-initiated SSO. e.g. Sign In using Salesforce

7.Enter IdP Entity ID as your SAML IdP Issuer i.e. 

8.Enter IdP Login URL as SP-Initiated Redirect Endpoint” URL i.e. 

9.Enter IdP Logout URL i.e. e.g.

10.Enter IdP Certificate content.

11.You will see EchoSign SAML Service Provider (SP) Information. Note down these URLs as you will need them in Salesforce side Configuration.

12.Click Save Changes button to save the settings.


Step 3 :Configure salesforce connect app:- 

  1. Log in as an Administrator, and navigate to Setup | App Setup | Create | Apps
  2. Under Connected Apps section, click New.
  3. Under Basic Information,
    1. Provide Connected App Name
    2. The field API Name is auto-populated
    3. In the field Logo Image URL, select Choose one of our sample logos, find the logo, and copy past the logo URL. Or, enter your own URL.
    4. In the field Contact Email, enter your email address. 


Under Web App Settings,

  1. Select Enable SAML
  2. Enter Entity ID as
  3. Enter ACS URL as 
  4. Select Subject Type. e.g. Federation ID. Please note that SAML Subject must carry the same identity as of EchoSign user’s account ID i.e. email.
  5. In the field Name ID Format, keep the default selection (unspecified)
  6. In the field Issuer, keep the default value
  7. In the field Service Provider Certificate, keep the default (unselected)

  1. Save the settings.
  2. Go to Manage Apps | Connected Apps
  3. Select your App.
  4. Click Manage Profiles or Manage Permission Sets and add profiles/permission sets of users who can access this app.



IdP Initiated Login URL: It will be used to test the IdP initiated SSO. Right click IdP-Initiated Login URL, and copy the link into a notepad.

  1. Click Edit Policies 
  2. In the field Start URL, copy and paste the URL from Notepad.
  3. Click Save.
  4. SSO setup for EchoSign is complete.

After Configured the Policies, you can see the EchoSign App in App launcher as shown below.