Log in to Salesforce using Google Account

There might be a requirement where you want your users to log in to Salesforce using a Google account. In this post, we will implement the Single Sign-On with Google as an Authorization Provider so that we can log in to Salesforce using a Google account.

Steps to Implement

First, we need to enable My Domain in Salesforce. Enter My Domain in the Quick Find box and select My Domain under Company Settings. Enter the domain name in the text box and Check Availability. If it is available, click Register Domain. It might take 30 minutes. Once it is registered, click Deploy to Users. You can logout and login using the Domain URL to test it.

Login to Google Developers Console and click on Create Project. Enter the Project name on the new Project page and hit Create.

Create Project

In search box, Enter API and select APIs & Services.

Search APIs

Click on the OAuth consent screen from the left sidebar, select External and click Create. Enter the Application name and Authorized domains on the OAuth consent screen page. The Authorized domain should be your Salesforce domain created earlier. Click Save.

Click on Credentials from the left sidebar and click Create Credentials and select OAuth client id.

Create Credentials

Select the Application Type as Web Application. Enter Name and click Create. You should get the Client Id and Client Secret.

Client Id and Secret

Create Auth. Provider in Salesforce

In Salesforce, enter Auth in the Quick Find box and select Auth. Providers under Security Controls. Select Provider Type as Google. Enter Name and URL Suffix. Enter Consumer Key and Consumer Secret we just created earlier. For Registration Handler, Click on Automatically create a registration handler template. This will create an Apex default handler. We can modify it as per our business needs. I have changed the name of the Apex class to Google Handler. Also, I am assigning the Email as Username and Alias. Select any user for Execute Registration As. Keep remaining values as default and Hit Save.

Login to Salesforce using Google Account

After clicking Save button, we will get the Salesforce Configuration URLs at the bottom.

Copy the Callback URL. Go back to Credentials created in Google Developers Console and click Add URI under Authorized Redirect URI. Add copied Callback URL and click Save.

We are on the final step. Go to My Domain settings by entering My Domain in the Quick Find box and select My Domain under Company Settings. Hit Edit under Authentication Configuration. Select Google Auth. Provider we just created as Authentication Service and hit Save. We are almost done.

Registration Handler

GoogleHandler implements Auth.RegistrationHandler interface. As part of this interface, two methods createUser() and updateUser() are already added. There is another method canCreateUser() which will be executed before creating a new user. We can add some criteria before creating a user. For this demonstration, we can add a list of emails that should be allowed to create a new user as we don’t want any random user to log into our org using their Google credentials. I also updated the Username and Alias with the email id we get from Auth.UserData data.

GoogleHandler.apxc

//TODO:This autogenerated class includes the basics for a Registration
//Handler class. You will need to customize it to ensure it meets your needs and
//the data provided by the third party.

global class GoogleHandler 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>{'<Google Id you want to allow for registration>'};
		if(s.contains(data.email)) {
			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;
		}
		//The user is authorized, so create their Salesforce 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.email;
		u.email = data.email;
		u.lastName = data.lastName;
		u.firstName = data.firstName;
		String alias = data.email;
		//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);
	}
}

Log in to Salesforce using Google Account

After all the setup is done, we can hit the Domain URL and we should be able to see Google Auth. Provider on Login screen.

Login to Salesforce using Google Account

Click on it and you will be redirected to the Google Login page. We have not added any value for Scope in Auth. Provider. So the default Scope considered is email and profile. Hence Consent Screen won’t be displayed. Instead, while entering the Username, it should be mentioned that ‘To continue, Google will share name, email address… with Salesforce.com‘.

Login to Salesforce using Google Account

Enter the Username and Password. And we are done, you should be redirected to the Home page of your org. It might ask to Register your Mobile Number, just click I don’t want to register my mobile number.

This is how we can log in to Salesforce using Google Account. In case you don’t want to miss any posts, please Subscribe here.

You can check more implementations using Salesforce OOTB features here. Thanks!

3 thoughts on “Log in to Salesforce using Google Account”

  1. Did exactly the same and got 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

    Reply
    • Check the Apex Code properly. In order to make this code work, you need to provide list of email ids in canCreateUser() at line number 9. Or else, you can remove that check and return true from canCreateUser().

      Reply

Leave a Comment