May 11, 2014

Google Drive Authentication In Salesforce - Easy Steps (Authentication Part 2)

Now where comes part 2 of authentication. This time it's with Google Drive.

In this blog Authentication with Google is explained so developers can get started.

Step 1 : Create  account on google (hope you already have), then go to developer console to create a project. Now click on project which is newly created then click on APIs and auth > APIs and make Drive API "on".

Step 2 : Now "Create New Client ID " which will look something like this :


Now we will use this info in salesforce to authenticate.

Step 3 : Create this apex class in Salesforce

public class GoogleDriveController
{
    //Fetched from URL
    private String code ;
    private string key = '134427681112-ld4vp2l1jut3aj2fktip776081nhn8l3.apps.googleusercontent.com' ;
    private string secret = 'hdHNk4GjNtkR4nNL1SqCfRk_' ;
    private string redirect_uri = 'https://c.ap1.visual.force.com/apex/GoogleDrivePage' ;
    
    public GoogleDriveController()
    {
        code = ApexPages.currentPage().getParameters().get('code') ;
        //Get the access token once we have code
        if(code != '' && code != null)
        {
            AccessToken() ;
        }
    }
    
    public PageReference DriveAuth()
    {
        //Authenticating
        PageReference pg = new PageReference(GoogleDriveAuthUri (key , redirect_uri)) ;
        return pg ;
    }
    
    public String GoogleDriveAuthUri(String Clientkey,String redirect_uri)
    {
        String key = EncodingUtil.urlEncode(Clientkey,'UTF-8');
        String uri = EncodingUtil.urlEncode(redirect_uri,'UTF-8');
        String authuri = '';
        authuri = 'https://accounts.google.com/o/oauth2/auth?'+
        'client_id='+key+
        '&response_type=code'+
        '&scope=https://www.googleapis.com/auth/drive'+
        '&redirect_uri='+uri+
        '&state=security_token%3D138r5719ru3e1%26url%3Dhttps://oa2cb.example.com/myHome&'+
        '&login_hint=jsmith@example.com&'+
        'access_type=offline';
        return authuri;
    }
    
    
    public void AccessToken()
    {
        //Getting access token from google
        HttpRequest req = new HttpRequest();
        req.setMethod('POST');
        req.setEndpoint('https://accounts.google.com/o/oauth2/token');
        req.setHeader('content-type', 'application/x-www-form-urlencoded');
        String messageBody = 'code='+code+'&client_id='+key+'&client_secret='+secret+'&redirect_uri='+redirect_uri+'&grant_type=authorization_code';
        req.setHeader('Content-length', String.valueOf(messageBody.length()));
        req.setBody(messageBody);
        req.setTimeout(60*1000);

        Http h = new Http();
        String resp;
        HttpResponse res = h.send(req);
        resp = res.getBody();
        
        System.debug(' You can parse the response to get the access token ::: ' + resp);
   }
}


Step 4 : Create this visualforce page (GoogleDrivePage) in Salesforce



    
        
    




Step 5 : Replace the code :

You can replace these three variables according to your settings (created in step 2)

private string key = '134427681112-ld4vp2l1jut3aj2fktip776081nhn8l3.apps.googleusercontent.com' ;
private string secret = 'hdHNk4GjNtkR4nNL1SqCfRk_' ;
private string redirect_uri = 'https://c.ap1.visual.force.com/apex/GoogleDrivePage' ;

Step 6 : Don't forget to create remote site setting :


Step 7 : All set to go, now hit the page "https:// ..... /apex/GoogleDrivePage", make sure your debug is on. Once authenticated with google debug will print the access token.


Now you can use this access token for further requests.

Please note, code is not beautified as this is just to explain how you can authenticate google with salesforce. A lot more creativity can be applied here.


Happy Coding!!

7 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Nice one Ankit...

    Can u please give an example code of how to use access_token and access files/folder in google drive..

    Thank you

    ReplyDelete

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Hey Ankit ,

    Thank you so much for sharing the knowledge. I just followed your steps which you have mention , It's working as expected. Just wanted to know how its assigning the auth code to "code" variable in the above code ? If you don't mind can you just explain that ?

    Thanks,
    Soumya Behera

    ReplyDelete
  5. I was finding this code for a long time. Thanks for this code. affordable IT solutions

    ReplyDelete
  6. Hi, I am getting error "error": "invalid_grant","error_description": "Code was already redeemed."
    please help me.

    ReplyDelete
  7. Very informative blog and very useful article thank you for sharing with us , keep posting learn more about salesforce training,salesforce online training

    ReplyDelete