Salesforce SSO JIT with AXIOM

In this blog, i am going to explain the how to configure the Just-in-Time Provisioning for SAML with AXIOM. With just-in-time provisioning, the end user identity is provisioned (created or updated) at the service provider the first time the end user tries to access the service provider’s service—without the need for prior identity provisioning activity between the identity provider and the service provider. With salesforce Just-In-Time provisioning you can create both portal users and regular users.

Step 1: – Enabled My Domain

To enable the custom domain
Go to setup –> Administer ->Domain Management->My Domain –> create your domain and deploy user. If you have already custom domain you can ignore this step.

Step 2: – Download the certification from Idp.

In order to configure the salesforce SSO, you need certificate from the IDP . in Our case Axiom is the IDP go to the below UR

https://axiomsso.herokuapp.com/SamlIdpHome.action

download the Download the Identity Provider Certificate

Step 3: Federated Single Sign-On Using SAML

Navigate to “Setup | Security Controls | Single Sign-On Settings” and check “SAML Enabled” option.

Step 4: – SAML Single Sign-On Settings

Now you need to configure the SAML Single Sign-On Settings. go to setting ->Security Controls ->Single Sign-On Settings->SAML Single Sign-On Settings-> Click New

Complete the details as describes below

1.Name :- < Any Name is fine > . In this example Axiom Just IN
2.API Name :- < Auto populate from Name >
3.SAML Version :- Default 2.0 Salesforce won’t support SAML 1.0
4.Issuer:- https://axiomsso.herokuapp.com
5.Entity Id:-https://saml.salesforce.com
6.Identity Provider Certificate: – Upload the Axiom Certificate which is downloaded in step 2
7.SAML Identity Type: – Select Assertion contains the Federation ID from the User object
8.SAML Identity Location : – Select Identity is in the NameIdentifier element of the Subject statement
9.Service Provider Initiated Request Binding: – Select Http Post
10.Identity Provider Login URL:- http://axiomsso.herokuapp.com/RequestSamlResponse.action

11. Under “Just-in-time User Provisioning” section

Check “User Provisioning Enabled” checkbox and select User Provisioning Type as standard.

After saving the configuration looks below

10

 

 

Step 5: – Configured IDP (Axiom )
go to https://axiomsso.herokuapp.com/Home.action expand “SAML Identity Provider & Tester ” section. Click on the “generate a SAML Response” link to configure the IDP

1.SAML Version:- 2.0
2.Username OR Federated ID: – TestUserforDemo
3.User ID Location: – Subject
4.Issuer:- https://axiomsso.herokuapp.com
5.Entity Id:- https://saml.salesforce.com
6.SSO Start Page:- http://axiomsso.herokuapp.com/RequestSamlResponse.action

7.Recipient URL:-
https://ltngdev-dev-ed.my.salesforce.com?so=00D41000000F5pm
8.User Type: – Standard

9. in “Additional Attributes” add the User information to create a salesforce user on the fly.

Note :

– If you are creating JIT Provisioning for Comunity you need to pass other “Additional Attributes” like Contact and Account details

After completing its looks as shown below.

1112

Click On “Request SAML response” to see the to generate SAML response. After Click on “Request SAML response,”  you will see output as shown below

13.PNG

Now to test the SSO Click on “Login ” Button. It will create a new user in the salesforce upon login on the fly.

 

-: Salesforce Apex Setup Audit trail: –

Starting with Winter ’16, Salesforce allowing access Setup Audit Trail object via API. Which is having access audit trail data more than 6 months but no official confirmation on how much you can go into history.
SetupAuditTrail is not a supported standard controller. Its support only queries and retrieve API calls.
You can use SOQL joins to get the information you need more quickly. For example, running SELECT CreatedBy.Name FROM SetupAuditTrail returns the first and last names of the people to make changes in Setup.
You can use where Cause and Order By Cause to perform an operation on data retrieval.
SELECT CreatedDate, CreatedBy.Username, Display, Section, Action, DelegateUser FROM SetupAuditTrail WHERE CreatedDate >= 2016-09-10T00:00:00Z AND CreatedDate <= 2016-10-01T00:00:00Z ORDER BY CreatedDate DESC.
Aggregate queries aren’t supported on SetupAuditTrail object.
Fields Supported: –
SetupAuditTrail Objects supports these fields namely Action, DelegateUser, Display, Section,
Examples: –
List listAudits = [SELECT Id,  Action, CreatedBy.Name, CreatedDate,Display,Section FROM SetupAuditTrail WHERE CreatedBy.Email LIKE ‘%abc.com%’];
Another Example with Last few years information.
            SELECT Id,Action,CreatedBy.Name,CreatedDate,Display,Section FROM SetupAuditTrail WHERE CreatedDate = LAST_N_YEARS:8 Order By CreatedDate DESC   Limit 10
Here is the visual force page UI

Here is Github URL for the complete example.












Salesforce Auth Provider – Twitter

In this blog post, we are going to see how to configure the twitter as auth provider to login into salesforce.

Registering new OAuth app in Twitter:-

1: go to https://apps.twitter.com/
2: Click on create a new app and fill the details under application details.
3.Name –<any meaning full name is fine >
4.Description * – <description about your application >
5.Website * – < your application website >
6.Callback URL – < leave it blank at this stage. we need to update this one with salesforce callback URL
7.Click on “Developer Agreement” terms and conditions then click on Create your twitter application.
After saving applications looks as shown below.

Now go to your application click on Keys and Access tokens tab to get your Consumer Key and Consumer Secret which are required to configure in salesforce auth provider.

Configuring Auth Provider in Salesforce:-

Now you need to configure the Twitter auth provider in salesforce.

Login into salesforce , Go to –> Setup –>Security Controls –> Auth. Providers –> Click on New from the Provider Type select Twitter. Fill the details as shown below.
1.Name – give it as Twitter
2.URL Suffix – give it as Twitter
3.Consumer Key – which your got from Keys and Access tokens tab from twitter application
4.Consumer Secret – which your got from Keys and Access tokens tab from twitter application
5.Custom Error URL leave it blank
6.Custom Logout URL leave it blank
7.Registration Handler – Click on Auto Generate
8.Execute Registration As Any System admin user
9.Portal – Leave it blank
10 .Icon URL – Leave it blank

 


Updating call back URL in the Twitter application:-

now you need to update the callback URL in twitter application which got it from salesforce

go to twitter application which you created earlier -> click on Settings tabs -> update the callback URL with the salesforce callback URL as shown below. then click on update settings.


Configure Auth Provider in My domain:-

Go to Setup -> Domain Management -> My Domain under
“Authentication Configuration” setting Click edit check twitter in “Authentication Service” then save it.

Now go to your salesforce domain login URL you can option to login using twitter as shown below


Once click on Login using twitter it will redirect to the twitter authentication page, click on sign in it will redirect to salesforce.

 

Issue 1: – Twitter OAuth won’t share the user email as part of the OAuth API request. To solve this follow these steps

Go to https://support.twitter.com/forms/platform
Select “I need access to special permissions”
Enter Application Name and ID. These can be obtained via https://apps.twitter.com/ — the application ID is the numeric part in the browser’s address bar after you click your app.
Permissions Request: “Email address”
Submit & wait for response
After your request is granted, an addition permission setting is added in your twitter app’s “Permission” section. Go to “Additional Permissions” and just tick the check box for “Request email addresses from users”.

Issue 2: –
The Twitter won’t support refresh token as per the document.

 

 

Salesforce Auth Provide – LinkedIn

In this blog, I am going to explain how to configure salesforce social sign on with LinkedIn. Salesforce has a number of social sign-on options like google, Facebook, and LinkedIn etc.Salesforce social sign gives users the option to sign-up and login on salesforce using their account on a social network like Facebook, Twitter, or Google+. Social Sign has a number of advantages like Pre-Validated Email, rich user profile date, One Click experiences and etc. . . .

How does Social Login work?

Social Login is a simple process, with the following steps.

1. The user enters your application and selects the desired social network provider.
2. A login request is sent to the social network provider.
3. Once the social network provider confirms the user’s identity, a current user will get access to your application.
4. A new user will be registered as a new user and then logged into the application.
Prerequisites:-

Custom Domain should be created and enabled for users.

Step 1: Creating LinkedIn Application.

Now we will see how to create LinkedIn Application. In order to enable the LinkedIn application first, log into the LinkedIn Developer Console and create a new LinkedIn Application by clicking the “Create Application” button and fill the information as explained below.

Name The name of your application.
Application Use Pick the intended use of your application.
Website URL The base URL of salesforce.

Click “Submit” to finish creating the new application.
Step 2: Enable LinkedIn permissions

In order to use the new LinkedIn Application with Salesforce, you need to enable the correct LinkedIn permissions.Under the “Default Application Permissions” section, enable the r_basicprofile and the r_emailaddress, rw_company_admin permissions. These permissions allow salesforce to access the basic profile properties like email and first, middle, and last name.


Please take note of Client Id and Client Secrete which will be used in Salesforce auth provides creation process.

We will be updating LinkedIn OAuth Setting later after creating auth providers in Salesforce

Step 3: Defining LinkedIn Auth Provider in Salesforce

To Setup auth Provide in Salesforce Go to setup->Security control->Auth. Providers select LinkedIn in the provider and fill the information as shown below.


1.Name: Desire name as you wish, but good to keep as Auth Provider name i.e LinkedIn
2.URL Suffix: Auto Populated based on Name
3.Consumer Key: Consumer key which you got in LinkedIn Application
4.Consumer Secret: Consumer key which you got in LinkedIn Application
5.Authorize Endpoint URL: Optional, leave it blank.Authorization URL from Linked
6.Token Endpoint URL: Optional, leave it blank OAuth token URL from LinkedIn.
7.User Info Endpoint URL: Optional, leave it blank.URL to change the values requested from LinkedIn’s profile API.
8.Default Scopes: Optional, leave it blank. Default Scopes to enter a supported value or several space-separated values that represent the information you get from LinkedIn.
9.Custom Error URL: Optional, leave it blank.Custom Error URL for the provider to use to report any errors.

10.Custom Logout URL: Optional, leave it blank. Custom Logout URL to provide a specific destination for users after they log out if they authenticated using the SSO flow.
11 .Registration Handler: Apex class as the Registration Handler class. Or click Automatically create a registration handler template to create an Apex class template for the registration handler. Later we are going to edit this class
12 .Execute Registration As select the user that runs the Apex handler class. The user must have the “Manage Users” permission.
13.Portals: Include in any portals in you wish to
14.Icon URL: field to add a path to an icon to display as a button on the login page for a community.

After saving salesforce will generate several Configuration URL

Test-Only Initialization URL—Admins use this URL to ensure that the third-party provider is set up correctly. The admin opens this URL in a browser, signs into the third party, and is redirected back to Salesforce with a map of attributes. You will able to see sample data as shown below.


Single Sign-On Initialization URL—Use this URL to perform SSO into Salesforce from a third party (using third-party credentials).

Existing User Linking URL—Use this URL to link existing Salesforce users to a third-party account. The user opens this URL in a browser, signs into the third party, signs into Salesforce and approves the link

OAuth-Only Initialization URL—Use this URL to obtain OAuth access tokens for a third party. Users must authenticate with Salesforce for the third-party service to get a token.

Callback URL—Use the callback URL for the endpoint that the authentication provider calls back to for configuration. The authentication provider has to redirect to the callback URL with information for each client configuration URL

Step 4: Updating OAuth URL in Previously created LinkedIn Application

Copy the Callback URL and then go back to the LinkedIn application. Paste it in the OAuth 2.0 redirect URLs value as show below the update the application.


Step 5: Configure Auth Provides as Login Options.

You can configure the Auth Provide from Communities or from your Domain Page.
Here we are going to see how to configure form Domain Page.

Go to Setup –> Domain Management — My Domain. Edit Authentication Configuration then select the LinkedIn Check box and save it.

Step 6: Login into Salesforce with LinkedIn Auth Provider

Go to your Domain login page to login with LinkedIn as shown below.

Now Click Log in by using LinkedIn. You will see an error like below. No worries, It expected behavior.

Let’s fix it now.

Step 7: Understanding and Updating System generated Registration Handler

To Set up Sign sign on you need to implement Auth. RegistrationHandler interface which is having the definition to create or update the user date appropriately.

Update the AuthRegigisration handler with the below code.

// This Class is template
// TODO : Modify create and update user logic based requirement
// TODO : Account and Contact Updated based on requirement .
global class AutocreatedRegHandler1486767418304 implements Auth.RegistrationHandler{

global User createUser(Id portalId, Auth.UserData data){

if (data.provider==’LinkedIn’) {
// Create Account
Account a= new Account(name = ‘LinkedIn’);
insert a ;
// Create contact
Contact c = new Contact();
c.accountId = a.Id;
c.firstName = data.firstName;
c.lastName = data.lastName;
insert c;

// Create User
User u = new User();
Profile p =[SELECT Id FROM profile WHERE name = ‘Marketing User’];
u.username = data.firstName+data.lastName+’@yourcompany.com.sandbox’;
u.email = data.email;
u.lastName = data.lastName;
u.firstName = data.firstName;
u.alias = data.firstName.substring(0, Math.min(data.firstName.length(), 5));
u.languagelocalekey = UserInfo.getLocale();
u.localesidkey = UserInfo.getLocale();
u.emailEncodingKey = ‘UTF-8’;
u.timeZoneSidKey = ‘America/Los_Angeles’;
u.profileId = p.Id;

return u;
}else{
return null ;

}

}

global void updateUser(Id userId, Id portalId, Auth.UserData data){
User u = new User(id = userId);
u.lastName = data.lastName;
u.firstName = data.firstName;
update u;
}
}
Now You can able to login into Salesforce with LinkedIn . Once you login with Linked in ,its going to create a new user as per the above code

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.

 

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-