Salesforce Auth Provide – Facebook

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

Prerequisites:-

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.email = data.email;
c.firstName = data.firstName;
c.lastName = data.lastName;
insert(c);

//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 + ‘@acmecorp.com’;
u.email = data.email;
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 + ‘@myorg.com’;
u.email = data.email;
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 + ‘@myorg.com’;
u.email = data.email;
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;
update(u);
}
}

 

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.

 

Advertisement

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(){
try{
system.debug(‘Key’+secretKey );
insert secretKey ;
}catch(Exception e ){
ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,e.getMessage());
ApexPages.addMessage(myMsg);
}
return null ;
}

public List<TenantSecret> getKeyHistory(){

return [Select Id ,
Description ,
Source ,
Type ,
version,
status
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=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css&#8221; />

<style>
.headerStyle{
background-color: PowderBlue!important;
background-image: none !important;
color: Black!important;
font-size:100% !important;
text-align:center;
font-family: Candara, Calibri, Segoe, ‘Segoe UI’, Optima, Arial, sans-serif;
font-size: 14px;
font-variant: normal;
font-weight: normal;
line-height: 17px;
}

.tdcls{
background-color:#f8f8ff!important;
background-image: none !important;
color: Black!important;
font-size:100% !important;
text-align:center;
font-family: Candara, Calibri, Segoe, ‘Segoe UI’, Optima, Arial, sans-serif;
font-size: 14px;
font-variant: normal;
font-weight: normal;
line-height: 17px;
}

</style>

<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:pageBlockSection>

</apex:pageBlock>

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

<table class=”table table-bordered table-inverse”>
<thead>
<tr>
<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>
</tr>
</thead>
<tbody>
<apex:repeat value=”{!KeyHistory}” var=”key”>
<tr>
<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>
</tr>
</apex:repeat>
</tbody>

</table>
</apex:outputPanel>

</apex:pageBlock>

</apex:form>

</apex:page>
Github URL for the code:-
https://github.com/rajamohanvakati/Platform-Encryption-

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 • Data.com • 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

SOQL/SOSL 

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.