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 = '' ;
    private string secret = 'hdHNk4GjNtkR4nNL1SqCfRk_' ;
    private string redirect_uri = '' ;
    public GoogleDriveController()
        code = ApexPages.currentPage().getParameters().get('code') ;
        //Get the access token once we have code
        if(code != '' && code != null)
            AccessToken() ;
    public PageReference DriveAuth()
        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 = ''+
        return authuri;
    public void AccessToken()
        //Getting access token from google
        HttpRequest req = new HttpRequest();
        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()));

        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 = '' ;
private string secret = 'hdHNk4GjNtkR4nNL1SqCfRk_' ;
private string redirect_uri = '' ;

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!!


  1. This comment has been removed by the author.

  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


  3. This comment has been removed by the author.

  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 ?

    Soumya Behera

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

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

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

  8. I acknowledge the author for his brilliant work for making this exceptionally useful and informative content to guide us.
    salesforce form builder

  9. I have read your blog its very attractive and impressive. I like your blog salesforce Online Training Bangalore

  10. What should be value of "code" to be passed as parameter?

    --> ApexPages.currentPage().getParameters().get('code')

    1. when you call DriveAuth() method it returns a new Page and url is also changed. In which you find code value.
      Or you can call google provide an authentication code for requesting access token.

  11. The information which you have provided is very good. It is very useful who is looking for salesforce Online Training Bangalore

  12. Great article. Do you have any idea, how can I allow public users to upload files into my GDrive.

  13. No matter what State we are using in above code, we are always getting invalid state error. Will you be able to guide us on this?

  14. I am getting 401 error (Unauthorized user) while connecting with google drive API. Please help on this.

  15. Thanks for sharing, nice post! Post really provice useful information!

    Giaonhan247 chuyên dịch vụ mua hàng mỹ từ dịch vụ order hàng mỹ hay nhận mua nước hoa pháp từ website nổi tiếng hàng đầu nước Mỹ mua hàng ebay ship về VN uy tín, giá rẻ.

  16. Nice tip. Keep sharing such ideas! Make sure to check this awesome online audio converter.

  17. I cannot see the page code. Can you please share it.