Monday, 2 September 2019

Handling MIXED_DML_OPERATION Exception in Salesforce

you can easily run into this error if you are trying to perform DML on setup and non-setup objects in the  same transaction.

Non-Setup objects are standard objects like Account or any custom object.

Setup objects are Group1,GroupMember,QueueSObject,User2,UserRole, UserTerritory,Territory, etc..

ex :
you cannot insert an account and then insert a user or a group members in a single transaction.

1. Avoid MIXED_DML_OPERATION using system.runAs in test classes.

ex :

@isTest
static  void test_mixed_dmlbug() { 
    User u;
    Account a;     
    User thisUser = [ select Id from User where Id = :UserInfo.getUserId() ];
    System.runAs ( thisUser ) {
        Profile p = [select id from profile where name='(some profile)'];
        UserRole r = [Select id from userrole where name='(some role)'];
        u = new User(alias = 'standt', email='standarduser@testorg.com',
            emailencodingkey='UTF-8', lastname='Testing',
            languagelocalekey='en_US',
            localesidkey='en_US', profileid = p.Id, userroleid = r.Id,
            timezonesidkey='America/Los_Angeles',
            username='standarduser@testorg.com');
        a = new Account(Firstname='Terry', Lastname='Testperson');
        insert a;
    }
    System.runAs(u) {
        a.PersonEmail = 'test@madeupaddress.com';
        update a;
    }

}

2. Avoid MIXED_DML_OPERATION Exception by using Future Method.

ex : 

trigger Automatecontact on Account(after insert) {
     List<contact> lc = new List<contact>();

for (Account acc : Trigger.new) {
   lc.add( new contact(lastname ='dk',accountId =acc.id) );
}
insert lc;

UtilClass.userInsertWithRole('dineshd@outlook.com', 'Dinesh','dineshd@outlook.com', 'Dineshdk');

}
public class UtilClass {
  @future
  public static void userInsertWithRole(String uname, String al, String em, String lname)
   {
Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
UserRole r = [SELECT Id FROM UserRole WHERE Name='COO'];
// Create new user with a non-null user role ID
User u = new User(alias = al, email=em,
emailencodingkey='UTF-8', lastname=lname,
languagelocalekey='en_US',
localesidkey='en_US', profileid = p.Id, userroleid = r.Id,
timezonesidkey='America/Los_Angeles',
username=uname);
insert u;
  }
 }



Note :

System.RunAs(User)

1.The system method runAs enables you to write test methods that change the user context to an existing user or a new user.

2.The original system context is started again after all runAs test methods complete.

Advantage of Trigger Framework in Salesforce

According to trigger framework
1) we should create single trigger for each object.
2) One handler class which will call Action
3) Create one action class with business logic same function you can use for other activity also. You can call from VF page  or batch job if required.

1) One Trigger Per Object
A single Apex Trigger is all you need for one particular object. If you develop multiple Triggers for a single object, you have no way of controlling the order of execution if those Triggers can run in the same contexts

2) Logic-less Triggers
If you write methods in your Triggers, those can’t be exposed for test purposes. You also can’t expose logic to be re-used anywhere else in your org.

3) Context-Specific Handler Methods
Create context-specific handler methods in Trigger handlers

4) Bulkify your Code
Bulkifying Apex code refers to the concept of making sure the code properly handles more than one record at a time.

5) Avoid SOQL Queries or DML statements inside FOR Loops
An individual Apex request gets a maximum of 100 SOQL queries before exceeding that governor limit. So if this trigger is invoked by a batch of more than 100 Account records, the governor limit will throw a runtime exception

6) Using Collections, Streamlining Queries, and Efficient For Loops
It is important to use Apex Collections to efficiently query data and store the data in memory. A combination of using collections and streamlining SOQL queries can substantially help writing efficient Apex code and avoid governor limits

7) Querying Large Data Sets
The total number of records that can be returned by SOQL queries in a request is 50,000. If returning a large set of queries causes you to exceed your heap limit, then a SOQL query for loop must be used instead. It can process multiple batches of records through the use of internal calls to query and queryMore

8) Use @future Appropriately
It is critical to write your Apex code to efficiently handle bulk or many records at a time. This is also true for asynchronous Apex methods (those annotated with the @future keyword). The differences between synchronous and asynchronous Apex can be found

9) Avoid Hardcoding IDs
When deploying Apex code between sandbox and production environments, or installing Force.com AppExchange packages, it is essential to avoid hardcoding IDs in the Apex code. By doing so, if the record IDs change between environments, the logic can dynamically identify the proper data to operate against and not fail


Custom Iterator (Iterable) in Batch Apex

1.If you use an iterable the governor limit for the total number of records retrieved by soql queries is still enforced.

2.if your code accesses external objects and is used in batch Apex, use iterable<sobject> instead of Database.QueryLocator.

global class CustomIterable implements Iterator<Contact>{

  List<Contact> con {get;set;}
   Integer i {get;set;}
 
   public CustomIterable(){
      con = [select Id,LastName From Contact LIMIT 5];
  i=0;
   }
     // This is Iterator interface hasNext() method, it will
// return true if the list 'con' contains records else it
// will return false;

   global boolean hasNext(){
      if(i>=con.size()){
    return false;
  }else{
    return true;
  }
   }
 
   // This is Iterator interface next() method, it will keep on
   // returning next element on the list until integer i reaches 5
   // and 5 in if loop is the size of the list returned by soql query
   // in above code
 
   global Contact next(){
     if(i==5){return null;}
i++;
return con[i-1];
   }
 
}

Note :
If your code accesses external objects and used in batch Apex, use Iterable<sObject> instead of Database.QueryLocator.

In Batch Apex , the start method return a Database.QueryLocator ,but you can return an Iterable.

global class batchClass implements Database.batchable<Contact>{
 global Iterable<Contact> start(Database.batchableContext info){
   return new CustomIterable();
 }
 global void execute(Database.batchableContext info,List<Contact> scope){
    List<Contact> conToUpdate = new List<Contact>();
for (Contact c :scope){
   c.LastName='Test123';
   conToUpdate.add(c);
}
update conToUpdate;
 }
 global void finish(Database.batchableContext info){

 }
}

Note :
1. Use the Database.QueryLocator object when you are using a simple query to generate the scope of objects used in the batch job. In this case, the SOQL data row limit will be bypassed.

2. Use iterable object when you have complex criteria to process the records.

External ID in Salesforce

The External ID field allows you to store unique record IDs from an external system,typically for integration purposes.

If we create External Id field, it will be indexed by default by salesforce.

During upsert operation

1. If External Ids are matched, it will update the records.
2. If External Ids are not matched, it will create a new record.
3. If External Ids are matched more than once,it will throw an error.

The fields with below data types can only be external Id

1.Number
2.Text
3.Email

You can designate up to 25 External ID fields per object.

External Ids are set with the unique property so that the IDs will be unique to each roecord.

Note :
Unique fields are not used in the UPSERT . it determine the uniqueness.

Indirect Lookup Relationship vs External Lookup Relationship

Types of relationships in salesforce :
======================================
1.Master - detail relationship
2. Lookup relationship
3. self- relationship
4. External lookup relationship
5. Indirect lookup relationship
6. Many-to-many relationship (junction object)
7. Hierarchical relationship

Indirect lookup relationship :
=====================
Indirect lookup relationship links a child external object to a parent standard or custom object.

you select a custom unique, external ID field on the parent object to match against the child's indirect lookup relationship field,whose values are determined by the specified External Column Name.

In Indirect lookup relationship, Salesforce standard or custom object will be the parent and External Object will be the child.

External lookup relationship :
=====================
External lookup relationship links a child standard,custom or external object to a parent external object.

The values of the standard External ID field on the parent external object are matched against the values of the external lookup relationship field.For a child external object, the values of the external lookup relationship field come from the specified External Column Name.

In External lookup relationship, External Object will be Parent.

Sunday, 11 August 2019

OAUTH AUTHENTICATION IN SALESFORCE


OAuth endpoints are the URLs that you use to make OAuth
authentication requests to Salesforce. When your application
makes an authentication request,make sure you're using the
correct Salesforce OAuth endpoints.

The primary endpoints are :

Authorization : https://login.salesforce.com/services/oauth2/authorize

Token :https://login.salesforce.com/services/oauth2/token

Revoke : https://login.salesforce.com/services/oauth2/revoke



OAUTH 2.0 Web Server Authentication Flow :
===========================================
1. Request Authorization Code
 
   https://login.salesforce.com/services/oauth2/authorize?
    client_id = consumer key &
redirect_uri=call back Url
response_type=code

 The response_type is code , indicating that we are using the authorization code grant type.

 your application directs the browser to the Salesforce Sign-in Page.where the
 user authenticates.

 The browser receives an authorization code from your salesforce authorization server.

 The authorization code is passed to your application.

 https://localhost:5001/salesforce/callback?code=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

 Your application sends this code to salesforce, and salesforce returns
 access token and optionally a refresh token.

 https://login.salesforce.com/services/oauth2/token?
   client_id     = consumerkey &
   client_secret = Consumer secret &
   redirect_uri  = callback_url    &
   grant_type    = authorization_code &
   code          = authorization code
 
 grant_type is authorization_code,indicating that we are using the
authorization code grant type.

code is the authorization code that you got from the /authorize endpoint.

 If the code is still valid ,your application will receive back access token.

 {
   "access_token": "eyJhbG[...]9pDQ",
    "token_type": "Bearer",
    "expires_in": 3600,
   "refresh_token": "eyJhbG[...]9pDQ",
   "instance_url": "https:n57.salesforce.com"
 }
 

 your application can now use these tokens to call the resource server(Salesforce)
 on behalf of user.

 Note :
 1. This flow is mainly used by applications hosted on web server.
 2.This flow is not recommended for application (like ETL or middleware's)
 which will access salesforce using APIS's and no UI is involved.
 3.This flow uses a client secret (CS) as an extra authorization
 parameter to prevent spoofing servers.
 4.This flow should be used for any serever/cloud applications.


 OAUTH 2.0 User Agent Flow :
 ===========================
 1. your application directs the browser to the Salesforce sign-in Page,
 where the user authenticates.

 https://login.salesforce.com/services/oauth2/authorize?
   client_id= consumer key &
   redirect_uri = callback url,
   response_type = token

 2.Salesforce redirects the browser back to the specified redirect URI,
 along with access token as a hash fragment in the URI.

 http://localhost:8080/#access_token=eyJhb[...]erw&token_type=Bearer&expires_in=3600

 {
   "access_token": "eyJhbG[...]9pDQ",
    "token_type": "Bearer",
    "expires_in": 3600,
   "refresh_token": "eyJhbG[...]9pDQ",
   "instance_url": "https:n57.salesforce.com"
 }

 3.your application extracts the token from the URI.
 4.Your application can now use these tokens to call the resource server(salesforce)
 on behalf of user.

 Note : This flow is recommended when you build mobile
 and desktop application.

 The benefit of the flow is that salesforce issues a refresh token,
 meaning that even when your access token expires, you are able to
 obtain a new one by executing the refresh token flow.

 It allows a user to authenticate to a partner application
 using their salesforce login credentials.

 OAUTH 2.0 JWT Bearer Token Flow :
 =================================
 External application send request for access token by passing
 JWT token in body. SFDC server validate JWT and return access
 token to external app.

 This flow requires you to upload a certificate to your connected app
 that will be used to validate the JWT token.

 JWT token is basically a JSON file consisting of a header and
 claims object, where header contains the signature algorithm
 and the claims object contains specific information such as the
 username and consumer key.

 At the high level, you will then sign the JSON object with the Private
 key of your certificate and send the JWT to salesforce to obtain
 an access token.


 https://login.salesforce.com/services/oauth2/token
     assertion = JWT token
grant_type = urn:ietf:params:oauth:grant-type:jwt-bearer

{
   Header { "alg":"RS256"}
   Claims {
      "iss" : issuer= consumer key,
  "sub" : subject= username,
  "aud" : audience = login url (login.salesforce)
  "exp" expiry=epoch=Now+5 min
   }

}
 1.Base64url encoded the Header and JWT claims Set.
 2.Chain them divided with a "."
 3.Create a Signature by Signing the resulting string using SHA256 with RSA.
 4.Chain resulting string with signature divided with "."
 5.JWT is done

 Note :
 No refresh token is returned in this flow. So if access token
 expires then send request to generate access token again.

 OAUTH 2.0 SAML Bearer Assertion Flow :
 =====================================
 Important pre-requisite is that the connected app in salesforce
 has a certificate uploaded who's private key is used when signing
 the assertion.

 A SAML assertion is an XML security token issued by an identity provider
 and consumed by a service provider.

 if your organization uses a central access control such as an active
 directory or LDAP store, it is likely that you would SSO to authenticate
 to your application.

 In this scenario , you may also want to use the SAML assertion
 from your SSO flow to obtain an access token to salesforce.

 This flow takes the SAML assertion (an XML token issued by your IDP)
 and applies a digital signature to it using a certificate.

 https://login.salesforce.com/services/oauth2/token
        assertion = SAML assertion Base64 encoded
grant_type = urn:ietf:params:oauth:grant-type:saml2-bearer


{
  issuer = client_id
  audience=https://login.salesforce.com
  recipient = https://login.salesforce.com/services/oauth2/token
  subject = username
 
}
   
 The assertion must be signed according to the XML Signature specifications,
 using RSA and either SHA-1 or SHA-256.

 Note :
 This flow also return only access token not refresh token.

 SAML Assertion Flow :
 ========================
 Use the OAuth 2.0 Token endpoint when accessing Salesforce via the API using SAML.
 you can use the SAML assertion flow only inside a single org.
 you don't have to create a connected app to use this assertion flow.

 https://login.salesforce.com/services/oauth2/token?
      assertion_type = urn:oasis:names:tc:SAML:2.0:profiles:SSO:browser
  grant_type     = assertion
  assertion = SAML assertion
If you have SSO configured specially for the Salesforce org that your partner
application is authenticating to, you can also use SAML Assertion Flow.

The benefit of this flow is that you can use a Base-64 encoded , then URL encoded,
SAML assertion that is normally used for web single sign-on.
 


Note :
No refresh token is issued in this flow.

OAUTH 2.0 Username and Password flow :
======================================
The OAUTH 2.0 Username and Password flow quite simply issues an
access token in exchange for a username and password.

https://login.salesforce.com/services/oauth2/token
      client_id = consumer key
  clent_secret = secret
  grant_type = password
  username   = testUsersalesforce.com
  password  = mypassword
 
Note :
No refresh token is issued in this flow.
Avoid using this flow because you have to send username and password
un-encrypted to salesforce.

OAUTH 2.0 Refresh Token :
========================

https:login.salesforce.com/services/oauth2/token
       client_id = consumer key
       grant_type = refresh_token
       refresh_token = your token here
To obtain a new access token from a refresh token use the
OAUTH 2.0 Refresh token flow.

The OAuth 2.0 refresh token flow renews tokens issued by the
web server or user-agent flow.

Note
when a user is logging out of your application you can revoke
tokens by using "/revoke" endpoint.

https://login.salesforce.com/services/oauth2/revoke?

 token = access token

OAUTH 2.0 Device Authentication Flow :
=======================================
 It should be used when you want to allow access to salesforce
 for an application that runs on a device with limited capabilities.

 ex: Tv,IOT devices and connected aircon etc.

 In this flow device is requesting a "device" and "User" code from salesforce.

 https://login.salesforce.com/services/oauth2/token?
       client_id = Consumer Key
   response_type=device_code
 
 response_type : Value must be device_code for this flow.

 The user code should be displayed alongside the verification_url
 that is returned by salesforce.
{
 "device_code":"M01WRzlQaFI2ZzZCN3BzN1RUSTRjUDdNcHBnM2w3dHUuTVJBWVVMeVZxY21BOWhHTHBIaWlTLlE3ck​85eWpsbWZmaUJVTTZ0RnBZQWxYRWtSakhiOTsxMC4yMi4zNC45MjsxNDc3Njc0NDg3NTA1O1gxRDlTRUVU",
 "user_code":"X1D9SEET",
 "verification_uri":"https://acme.my.salesforce.com/connect",
 "interval":5
}

 The user working with a device navigates to the displayed URL
 on their mobile or laptop and enter the user code that was provided.

 They then log into salesforce and approve access to the application.

 https://login.salesforce.com/services/oauth2/token?
       grant_type = device
   client_id = consumer key
   code = device_code

code : should be used device_code which you got in previous response.

In the meantime ,the application running on the device should keep
polling salesforce (polling interval is also returned by salesforce)
and once the user has approved access,the application on the device
will get an access token is used.

{
"access_token": "00DD00000008Uw2!ARkAQGppKf6n.VwG.EnFSvi731qWh.7vKfaJjL7h49yutIC84gAsxM​rqcE81GjpTjQbDLkytl2ZwosNbIJwUS0X8ahiILj3e"
"refresh_token": "your token here"
"signature": "hJuYICd2IHsjyTcFqTYiOr8THmgDmrcjgWaMp13X6dY="
"scope": "api"
"instance_url": "https://yourInstance.salesforce.com"
"id": "https://login.salesforce.com/id/00DD00000008Uw2MAE/005D0000001cAGmIAM"
"token_type": "Bearer"
"issued_at": "1477674717112"
}

OAUTH 2.0 Asset Token Flow :
=============================
Client applications use the OAUTH 2.0 asset token flow to request
an asset token from Salesforce for connected devices.

This flow requires the device to obtain an access token (in any of the above ways)
and use this token alongside additional information to create an actor token.

This token contains valuable information about the asset which is then send to salesforce
where it is exchanged for an asset token.

Subsequent requests to protected resources at salesforce
can then be made with the asset token.

   

Sunday, 14 July 2019

single sign on (SSO)


single sign on (SSO)
===================
User just remember one username and password that will allow us to logon to all other different applications.

It's like having a magic key that automatically opens up all the other doors once you enter through one door.

Salesforce provides different options to configure single sign on.

1.Federated Authentication using SAML
2.Delegated Authentication
3.OpenID Connect

Main concepts in SSO

1.The concept of IDP/SP
2.The Concept of IDP Initiated login and SP initiated login.

IDP stands for Indentity provider and SP stands for service provider.

In IDP Init SSO the Federation process is initiated by the IDP sending an SAML Response to the SP.

In SP-Init, the SP generates an AuthRequest that is sent to the IDP as the first step in the Federation process and the IDP then responds with the SAML Response.

IDP initiated Login :
=====================
User can logon to IDP and then from there, clicks on links to access other systems(i.e SP).This is called IDP initiated login.

   user    ---->      Identity provider
                           |
   |
   |  SAMl Assertion
                          V
                        salesforce (SP)

SP Initiated Login :
=====================
User can go directly to an SP application to access the application.
In this case, SP will redirect the user toIDP login page where user will provider
his/her username and password, IDP will authenticate the user and pass control
back to SP asserting whether user is authenticated or not.SP will then allow
user to access the application.

Note : Identity provider is the instance where users have an active session.
And service provider is the one which identifies the certificate from
the identity provider saying the user is coming from the authenticated source.


                                              saml Auth Request
   user ---->  salesforce (sp)  ------>
                                              <-------   Identity provider
 saml assertion


Federated Authentication using SAML :
=====================================
1.Federated authentication uses SAML, an industry standard for secure integrations.Investing in SAML with Salesforce.com

2.org-wise level

3.Salesforce admins can enable.

Authentication and authorization between two entities : service provider and identity provider

The service provider agrees to trust the identity provider to authenticate users.

Note :

SAML stands for security Assertion Markup Language.

SAML is an XML-based protocol for exchanging identity and authorization information.

The SAML,which is basically XML documents that are going  to be exchanged. Some are going to be exchanged at setup time, and some are going to be exchnaged when you try to
login.

That XML has a packet of information that contains authentication information, but it's built into that XML data model essentially.

Just-in-time user Provisioning :
============================
The just-in-time provisioning is basically the idp has the authority to create or update user information inside of the service provider.


relay :
========
SP init does it carries your original destination that you were trying to get to as part of the relay state.

The RelayState is meant to direct the user after a successful login to a specific location in the application they're logging into. If you need to include query parameters,make sure they're URL encoded.

RelayState=var1%3Dvalue1%26var2%3Dvalue2

SAML Assertion Validator :
===========================
1. Available in single sign-on settings.
2. used to check for failed logins of sso.


Delegated Authentication Flow :
===============================
Delegated Authentication is specific to salesforce only(not industry standard)
where external webservice only retruns "TRUE" and "FALSE" saying Authentication is complete
or not.

1.Require salesforce support to enable.
2.Permission level.

Note:
when the user submits the login page with their credentials, Salesforce look up the user from the username.If Delegated Authentication(DA) is configured for this org and user,
we send the supplied password to the configured Delegated Authentication (DA)
endpoint for verification,otherwise we verify the password against the hash
we have on record for that user.Either way, if the password is successfully
verified,we create a session, issue the cookie, and redirect the user to
the requested page.


1. We can integrate with the LDAP server - Lightweight Directory Access Portocol or authenticate with the access token rather with the password.

2.We can also manage authentication at the permission level which gives us more flexibility.

3. with the above feature, we can set delegated authentication for particular users rest will use their salesforce credentials for login.

4.If user tries to login through online or API, salesforce checks permission settings and access settings after validating the UserName.

5.if user has enabled the single sign on permission setting then salesforce doesn't validates the login credentials.Rather it makes an web service call to org for validating the login credentials.

6. When above permission setting is enabled then salesforce no longer manages the password policies

ex : Password must be required minimum length.

7.Then delegated authentication comes into action, the endpoint service enforces the policies for password.

Note :
The webService validates username,password and Source IP

Source IP : The IP address that originated the login request.


security Modes :
================
1.Simple Passwords (User salesforce login page)
2.Tokens ( Private login page on your company webserver that may be behind your corporate firewall)
3.Mixed (use mobile and client apps)


OpenID Connect :
====================

OpenID Connect is a modern Identity Protocol that leverages OAUTH.

It provides an ID token and UserInfo endpoint.

you can use it for single sign-on (SSO).

Salesforce can act as an OpenID Connect client.

 ex: Sign in with Google.

Salesforce can act as an OpenID connect Provider.

Example Login with Salesforce.


OpenID Connect - for social Sign-on into the org.
 Login to salesforce org with Google+.

 Steps for social sign-on with Google+ into Enterprise Org.

 1. Setup MyDomain in the org.
 2.Configure an OpenID Connect type Authentication provider  pointing to Google.
 3.Set a google plus user ID field on user record - for account linking.
 4.Update a user record with a valid google plus userID.
 5.Configure enterprise branding page to enable Login with Google.
 6.Test Login with Google into the enterprise org.


OpenID Connect - For salesforce login into the community.

 Login to community with any Salesforce org.

 Steps for Single Sign On into Community with any Salesforce Org.

 1. Setup OpenID Connect Auth Provider pointing to a Connected  App in IDP.
 2.Registration Handler code can do user checks based on Email  or FederationID.
 3.Set the Community Login Page to use this Auth Provider.


 Authorization Request

 https://ogin.salesforce.com/services/oauth2/authorize

Authorization Response

https://www.example.com/oauth/callback/?

Token Request

Token Response

access_token
id_token

Note :
Client uses ID token to authenticate the end user.

The ID token is represented as a JSON Web Token (JWT).The JWT is singed using a JSON web signature and consist of three parts separated by "."

An ID token has the following syntax :

Base64(JOSE header).Base64(Payload).Base64(Signature)

Every Client must validate the ID-token it receives.It must validate the iss, aud and exp claims. The rest are optional if presented.

what OpenID connect adds?

1.ID token
2.UserInfo endpoint for getting  more user information
3.Standard set of scopes
4.Standardized implementation.

OAuth and OpenID Connect :
======================

Use OpenID Connect for (Authentication):

1.Logging the user in
2.Making your accounts avaialble in other systems

Use OAuth 2.0 for (Authorization) :

1.Granting access to your API
2.Getting access to user data in other systems.


Connected App :
=============

Consumer key is essentially the API key associated with
the application (Twitter, Facebook, etc.). This key
(or 'client ID', as Facebook calls it) is what
identifies the client. By the way, a client is a
website/service that is trying to access an end-user's
resources.

Consumer secret is the client password that is used to
authenticate with the authentication server, which is a
Twitter/Facebook/etc. server that authenticates the
client.

Access token is what is issued to the client once the client successfully authenticates itself (using the consumer key & secret). This access token defines the privileges of the client (what data the client can and cannot access). Now every time the client wants to access the end-user's data, the access token secret is sent with the access token as a password (similar to the consumer secret)