Login to Salesforce from Salesforce using Authentication Provider

There are many ways to login to your Salesforce instance, using Google, Facebook, Linked, Twitter and even from other Salesforce Organization. I am sure many of readers has multiple Salesforce instances and its hard to remember password of each. We can connect every Salesforce instances and login using only one. In this post we will see, how we can login to one Salesforce from other using built in Authentication provider from Salesforce.

Throughout this article I will use term “service provider Salesforce instance” for Organization where I need to go after login and “Authentication Provider instance” which will authenticate user and will act as source organization for login.

Enable MyDomain 

First step to start with Authentication Provider is to setup my domain in your “service provider Salesforce instance“. This step is important so that it will display all available Authentication provider for that Salesforce instance.

Create Connected app 

If you want to login from Facebook, LinkedIn or any other web application, you need to inform Salesforce that those applications are legitimate and this is very important piece of OAuth2. One of major difference between OAuth1 and OAuth2 is that OAuth2 provides scope where you can set what specific permission this Connected App will need.

Connected App also has “Consumer Key” and “Consumer Secret” which is equivalent to “username” and “password” for that App.

Other important setting, connected app has “Callback URL“. This is the URL where “Authentication Provider instance” should return after providing access. Even if somehow “Consumer Key” and “Consumer Secret” is compromised, it will return to Callback URL which is your application.

In this post we need “service provider Salesforce instance” to be logged in from “Authentication Provider instance“. So “Authentication Provider instance” should be able to identify that request is coming from “service provider Salesforce instance“. Therefore Connected App needs to be created in “service provider Salesforce instance” (SP).

To create Connected App in “service provider Salesforce instance“, Navigate to “Setup | Build | Create | Apps | Connected Apps” and click on New. Provide All information except “Callback URL”. We will comeback again on this step later to provide Callback URL.

Salesforce Connected App
Salesforce Connected App

Once you save this Connected app, it will provide “Consumer Key” and “Consumer Secret”, we need this information in next step.

Create Authorization Provider 

Its time to create Authorization Provider in “Authentication provider Salesforce instance (IDP)”.

Navigate to “Setup | Administer | Security Controls | Auth. Providers | Create New”.

Select “Salesforce” as provider Type.

We need to provide “Consumer Key” and “Consumer Secret” created in previous step. Also one important setting is “Default Scope“, it should have value as “refresh_token full”. “refresh_token” and “full” should be separated by space. Authorize Endpoint URL should be something like “https://AuthenticationProviderinstance/services/oauth2/authorize” and Token Endpoint URL “https://AuthenticationProviderinstance/services/oauth2/token“.

Click on “Automatically create a registration handler template”, it will generate one apex class, in my case auto generated apex class name is “AutocreatedRegHandler1432826053915”. Then Select User who should be used to execute this Apex class when user tries to login.

Salesforce Authentication Provider
Salesforce Authentication Provider

Set Callback URL in Connected App 

Once you save “Auth. Provider” in previous step, it will provide you list of URL as shown in below image. Copy Callback URL and edit Connected App we created in service provider Salesforce instance and set this URL.

Salesforce Authentication Provider Client Configuration
Salesforce Authentication Provider Client Configuration

you can even test your application using “Test-Only initialization URL”, however in our case we need to modify our Apex class, so need to wait.

Create field in User Object 

We are almost there, but we have one problem to address. When someone tries to login from “Authentication Provider instance”, how we will match which user from “Authentication Provider instance” matched with user in “service provider Salesforce instance” ? We will need to create one field on User object which will save username of other Salesforce instance. In this case, I have created field “Other Salesforce Org Username”. Once field is created, populate every user record so that we should be able to match them.

Update Auto generated Registration Handler Apex class 

Replace content of Apex class by below code, in our case class name is “AutocreatedRegHandler1432826053915”.

/**
*	@Author			:	Jitendra Zaa
*	@Date			:	5/29/2015
*	@Description 	:	Match User from Other Salesforce instance with this Salesforce.
*
**/
global class AutocreatedRegHandler1432826053915 implements Auth.RegistrationHandler{
	 /**
	 *	This method is used to match existing user, If not find then we can create new User.
	 *	This method will be executed only first time so that Salesforce can relate two users
	 */
	global User createUser(Id portalId, Auth.UserData data){
		User u = [SELECT ID FROM User Where Other_Salesforce_Org_Username__c = : data.username];
		return u;
	}

	/**
	*	Once Users are related, after that whenever user will return, this method wil be executed.
	*	If needed, we can perform any information needed.
	*	In this blog , we are not going to perform any operation in this method.
	*/
	global void updateUser(Id userId, Id portalId, Auth.UserData data){
	   //No Operation
	}
}

As you can see, this class implements interface “Auth.RegistrationHandler” which has contract for two methods named “createUser” and “updateUser”, other piece of code is commented to explain.

Add Salesforce button on Login Page 

Navigate to “Setup | Administer | Domain Management | My Domain | Authentication Configuration | Edit”.

This page will provide, list of all Authentication providers like LinkedIn, Facebook, Google, In our case Salesforce.

Salesforce Authentication Configuration in My Domain
Salesforce Authentication Configuration in My Domain

Now logout and navigate to Login page specific to your instance and you should be able to see all Authentication provider buttons for your instance. Pleas note that, Authentication provider button will not appear on “https://login.salesforce.com” page, it has to be Mydomain login URL.

This is sample of Login page, how it will look like.

Salesforce My Domain Login page
Salesforce My Domain Login page

Posted

in

by

Comments

34 responses to “Login to Salesforce from Salesforce using Authentication Provider”

  1. Sachin Avatar
    Sachin

    HI Jitendra,
    Can you please brief me out 1 thing, how my authentication provider instance will authenticate my other / target instance becaus every configuration which you have discussed here is for target/ current org. I am not able to get how this will allow me to login via other org into current org?

    1. Jitendra Zaa Avatar

      Hi Sachin, I have updated this article to make it more clear, If you want you can check this article as well – https://www.jitendrazaa.com/blog/salesforce/salesforce-to-salesforce-integration-using-canvas/

  2. Brad Avatar
    Brad

    Thank you!!

  3. sumit sachdeva Avatar
    sumit sachdeva

    Hi,

    We are trying to implement SSO using Facebook credentials. When we use the SSO URL, it redirects us to the FB login screen, where when we enter our credentials, it gives an error. Screenshot attached. Do you have any idea how to resolve it?

    When I check the debug logs, it is inserting the contact, inserting the user, but then fails with this error, giving no other information in the debug log.

    Any suggestions welcome 🙂

    1. Jitendra Zaa Avatar

      Hi Sumit, Can you please attach screenshot ?

  4. Mohd Anzar Avatar
    Mohd Anzar

    Hi,
    I am calling the method on the page and I am getting the Html code there. Any suggestion ?

  5. Sanjeev Soran Avatar
    Sanjeev Soran

    Hi,

    I want to know the way to modify SAML response before sending to SP to add the permission set name assigned to the user for the connected app to connect with SP.
    I found that it can be done using ConnectedAppPlugIn class. Please help with some sample.

    Thanks
    Sanjeev

    1. Sanjeev Soran Avatar
      Sanjeev Soran

      Any Suggestions?

      1. Jitendra Zaa Avatar

        You cannot intercept SAML reponse before reaching to SP, Handshaking of certificate / Authentication will fail. IP needs to have this permission. If you give some thoughts around security, its not possible.

  6. Surya Avatar
    Surya

    I have done everything you explained and in the end when I click on the button I am getting logged in to the same org rather that getting logged in to a different(expected) org. Can you please help where probably I could have done mistake? Where should the auth provider should be created?

  7. Rajesh Avatar
    Rajesh

    Hi Jitendra Zaa,
    I have done all your steps but finally i get this error…

    We can’t log you in because of the following error. For more information, contact your Salesforce administrator.
    CSRF: No CSRF cookie

    We can’t log you in because of the following error. For more information, contact your Salesforce administrator.
    CSRF: CSRF mismatch: Cookie 24420330048643426601489835138143-3899016716802188792, request -19060066950583086001489835731663-8855758307183285335

    How to fix?

    Pls help anyone…

  8. Lakshmi Avatar
    Lakshmi

    Hi Jitendra,
    I’m trying to do the authentication from a form through php and once the authentication is complete, I’m trying to post the form info to salesforce. Since I have to provide callback url, the control is going to callbackurl instead of the calling form/php. Do you know how I can solve this issue so I still can have the form information to post in the callback url or to go back to calling form/php instead of callback url?

  9. Ian Avatar
    Ian

    Confusing…

    The blog is not at all clear what should be done in what Org.

    I assume (but haven’t yet tried)

    Create Connected app = “service provider Salesforce instance”
    Create Authorization Provider = “Authentication Provider instance”
    Set Callback URL in Connected App = “service provider Salesforce instance”
    Create field in User Object = “Authentication Provider instance”
    Update Auto generated Registration Handler Apex class = “Authentication Provider instance”
    Add Salesforce button on Login Page = “service provider Salesforce instance”

    Can you update the blog to make this easier to follow, or at least confirm by above assumptions?

    1. Jitendra Zaa Avatar

      Hi Ian,
      Throughout this article I have used term “service provider Salesforce instance” for Organization where I need to go after login and “Authentication Provider instance” which will authenticate user and will act as source organization for login. Made some text bold , let me know if it helps.

    2. Nishant Sinha Avatar
      Nishant Sinha

      I feel something is not correct.
      When adding the “Salesforce button on Login Page” system will show all the Auth Provider list. Since we have created Auth. Provider in another org, this Org will not show that option.

  10. Binu Jose Avatar
    Binu Jose

    Hi Jitendra,

    Thank you for the detailed steps. I’m trying to set up a Salesforce based SSO for a community. I.e. a user with a Salesforce account on any org should be able to login to my community. While I’ve followed your steps to set up the SSO, from the login screen on the community, when I select “SSO Provider” button, I am taken to a page that shows me an error message:

    error=redirect_uri_mismatch&error_description=redirect_uri%20must%20match%20configuration

    Upon reading up, it is said that the redirect URL defined in the connected app sometimes takes a while to propagate across all the Salesforce instances and so this error could occur. It’s been more than 24 hours but I still run into the same error. Do you know of any other reason why this error could occur? Thanks.

  11. mithilesh dubey Avatar

    Hii Jitendra
    I’m getting an error saying
    “We can’t log you in because of the following error. For more information, contact your Salesforce administrator.

    REGISTRATION_HANDLER_ERROR: List has no rows for assignment to SObject”

    when i’m trying to login using REST.

    Awaiting response,
    Mithilesh

    1. saranddSaravanan Avatar

      Any update on REGISTRATION_HANDLER_ERROR? Please let us know.

      1. Lokesh Avatar
        Lokesh

        Hi I am also getting the same error

  12. Krishna Avatar
    Krishna

    Hi Jitendra,

    I have followed all the mentioned steps, when i try to login i get the below error

    We can’t log you in because of the following error. For more information, contact your Salesforce administrator.

    NO_ACCESS: Unable to find a user

    Please let me if i am missing anything here.

    Thank you very much!
    Krishna

  13. Anshul Gupta Avatar
    Anshul Gupta

    I followed the steps, also replaced the client Id with my consumer key but getting the following error:

    error=invalid_client_id&error_description=client%20identifier%20invalid

  14. Sai Avatar
    Sai

    Hi Jitendra,

    Thanks for the post. Is there any blog post for the below scenario

    Embed external web application in a custom tab. Once clicked on this custom tab the user should be automatically logged in and show this external web application with in this custom tab.

    If you can guide with some of your inputs or link to any of your blog post would be really helpful.

    Thanks, Sai

  15. Vivek Haddunoori Avatar
    Vivek Haddunoori

    Thanks Jitendra, this is helpful !

  16. Sai Pranay P Avatar
    Sai Pranay P

    Hi Jitendra,

    I have implemented the Identity provider using the steps given above, but I end-up with an error and now I am unable to login to my developer org. I am getting the following error.
    “Unable to Access Page
    The value of the “state” parameter contains a character that is not allowed or the value exceeds the maximum allowed length. Remove the character from the parameter value or reduce the value length and resubmit. If the error still persists, report it to our Customer Support team. Provide the URL of the page you were requesting as well as any other related information. ”

    This error occurred when I logged out and logged in to org.

    Could you please help me resolving the issue.

    Thanks in advance,
    –Pranay

    1. Puneeth Avatar
      Puneeth

      Hi, Where you able to fix this error? I am getting the same issue.

  17. Gupta Avatar
    Gupta

    keep on signing into same developer account if i enter wrong details.
    i put debug logs on Execute Registration As user.
    In the debug logs it never calls ceateUser method.

    1. Kiran Prabhakara Avatar
      Kiran Prabhakara

      Hi Gupta, I know this is my late post 🙂 Did you resolve this? I am getting same issue

    2. Kiran Prabhakara Avatar
      Kiran Prabhakara

      Were you able to fix this? I am facing same issue

  18. Priyanka Singh Avatar
    Priyanka Singh

    How to get authorization code in auth provider call after login. I am not able to get it in auth class. After outh code, do i need to make callout to get accesss token and refresh token.Please tell. Thanks

  19. Youstina Avatar
    Youstina

    I am looking to use OpenId to authenticate using third party credentials to access the SF Rest APIs.

    Would it work to use an Auth Provider with the Consumer and Client key of a Connected App in the same org? this way I can authenticate with a third party credentials to access the APIs?

  20. Desai Avatar
    Desai

    Hi all,

    I am getting the error of (ErrorCode=No_Oauth_State&ErrorDescription=State+was+not+sent+back) when I try to connect my IDP(PindIdentity) to Salesforce via OpenID.

    If anyone can help that would be great.

  21. Dipankar Avatar
    Dipankar

    For those of us getting 302 and followed by 401 as noted in the comments of many visitors.
    It may be due to the mydomain url not being used in the Auth provider and the named credentials instead one may be mistakenly typing the instance url from the browser, the instance url should be the my domain url and should have the …my… signature

  22. Charlie Faber Avatar
    Charlie Faber

    Thank you for this article, 7 years after it was written and still a huge help!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.