Thursday, 15 August 2013

Force.com and Google integration with oAuth Authentication





In this post I will be explaining how to integrate Google Calendar with Sales force.com.Once we are integrated,  the events in the Google Calendar will get synced with Sales force.

The summary of oAuth Authentication


First create an Api project in Google.

Redirect the user to Google oAuth Authentication url, Then will user asked to login to the Google.

Once the user successfully logged in then Google redirect the user to the application. While redirecting the user to application, Google add a code parameter in the url, that indicates the proof of authentication. The code is called authentication code.

The user then request for two other tokens: access token, refresh token. The access token will expire in one hour for offline based access and we use refresh token to get new access token after it expires. So we need to store the refresh token in the system for future access. Google recommends storing refresh token along with user id and making the user id as an indexed field in database. 


Step 1: Create an API Project in Google API Console

API Project determines which API the client is allowed to utilize from external application via oAuth authentication. 

Goto  https://code.google.com/apis/console/

Google ask you to sign in first

If you don’t have any project created then the below screen will get displayed.





Click on Create Project it will direct you to choose API for your project.
By default all the API services are disabled.


Click on the off button in next to the Calendar API and activate the Google Calendar API.
Click on the API Access on the sidebar.



Click on Create oAuth 2.0 Client ID button, It will ask you to enter the product name, logo,Branding info, home page with etc..

Click next and it will ask Client ID settings here choose Application Type as Web Application.

Click on More Option link

In the first text box enter the url to which Google redirect the user once Authentication is succeeded.
And click on Create Client ID.

This will create Client Id , Client secret etc. for API Project.


Step 2: Authenticate with Google from Sales force.com.
To authenticate with Google in oAuth authentication redirect the user to the url below.

https://accounts.google.com/o/oauth2/auth?access_type=offline&approval_prompt=force&client_id=<INSERT YOUR CLIENTID HERE>&redirect_uri=<INSERT YOUR REDIRECT URL HERE >&response_type=code&scope=https://www.googleapis.com/auth/calendar

This redirect uri should be same as the redirect url given in the API Project otherwise Google will reject the request.

Once the user is successfully redirected to Google the user will be prompted to enter the credentials and the user will be redirected to the redirect uri specified in the api project.The redirected url from Google contains code parameter as well. This code is the authentication code for the auth Authentication, this will be used in the later part for getting access token and refresh token.


Once you get the authentication code then we can request for the access token, refresh token.
For every API request to Google requires access token and this access token will expire in one hour for offline based access. To get new access token we need to make another request with help of refresh token to receive new access token.

To request for access token you need

1.Authentication code
2.Client Id, Client secret.
3. Redirect uri of your API project.
The apex code for getting new access and refresh token is give below. The response from Google is in the form of JSON object.

Before making the external request add the endpoint url to the sales force remote sites. The remotes sites can be found under setup-> Security Controls-> Remote Site Settings.

 

http htp = new http();//Creating instance of http object
HttpRequest htp_req =  new HttpRequest();//Creating instance of http request object
HttpResponse htp_res = new HttpResponse();//Creating instance of http response object
htp_req.setMethod('POST'); //Creating instance of http request type
htp_req.setEndPoint('https://accounts.google.com/o/oauth2/token');//To which url the request is made.
String body = 'code='+[insert authentication code]+'&&redirect_uri=[insert redirect uri here]&[insert client id here] &scope=&client_secret=[insert client secret here]&grant_type=authorization_code';
htp_req.setBody(body);
try
        {
            htp_res = htp.send(htp_req);            
            JSONParser parser = JSON.CreateParser(htp_res.getBody());
            while(parser.nextToken()!=null)
            {
                if(parser.getText()=='access_token')
                {
                    parser.nextToken();
                    accessToken = parser.getText();
                }
                if(parser.getText()=='refresh_token')
                {
                    parser.nextToken();
                    refreshToken = parser.getText();
                }
            }
        }
        catch(Exception ex)
        {
            System.debug(htp_res+','+ex.getMessage());
        }

Once we are received the access token and refresh token we can make all supported API request.
3.Sample API Request to get all calenders.


Example to List all the calendars from a Google account.

http hp = new http();

httpRequest req = new httpRequest();

httpResponse res = new httpResponse();

req.setMethod(‘GET’);


req.setHeader(‘Authorization’,’Bearer ‘+<INSERT ACCESS TOKEN HERE);


req.setEndPoint(‘https://www.googleapis.com/calendar/v3/users/me/calendarList‘);

try

{ 

res = hp.send(req);

return res.getBody();

}

catch(Exception e)

{

System.debug('********EXCEPTION**********'+e.getMessage());

return null;

}


The response JSON object contain the list of calendars for currently login.

Finally Google allows developers to test the api request in oAuth playground. This is just an environment to learn how to use API requests and see responses in real time.
The url for oAuth playground is : https://developers.google.com/oauthplayground

5 comments:

  1. What had you put in as the redirect URI? I need to Integrate salesforce and Google.

    ReplyDelete
    Replies
    1. basically the redirect uri is the url to which you have to redirect the user after successful authentication. Here i used my vf page url which process the logic after successful authentication.

      Delete
    2. So, you provided the Instance as well? How to overcome the issue of the instance. Suppose if it is not a ap1 and something else like na15?

      Delete
    3. And can we check the response in the Debug Log like we do in other webservice call-outs?

      Delete


  2. interesting blog. It would be great if you can provide more details about it. Thanks you

    Google App Integration Madurai

    ReplyDelete