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

22 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
  8. What should be value of "code" to be passed as parameter?

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

    ReplyDelete
    Replies
    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.

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

    ReplyDelete
  10. 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?

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

    ReplyDelete
  12. How can we get 'code' here??

    ReplyDelete
  13. 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ẻ.

    ReplyDelete
  14. Nice tip. Keep sharing such ideas! Make sure to check this awesome online audio converter. https://onlineconvertfree.com/converter/images/

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

    ReplyDelete
  16. 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ẻ.

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

    ReplyDelete
  18. Your code from Step 4 isn't appearing, I believe it's suppose to be this? (if you copy-paste this, make sure you change all "⍃" to "<")

    ⍃apex:page controller>="GoogleDriveController">
    ⍃apex:form>
    ⍃apex:pageblock>
    ⍃apex:commandbutton action="{!DriveAuth}" value="Google Drive Authentication"> ⍃/apex:commandbutton>
    ⍃/apex:pageblock>
    ⍃/apex:form>
    ⍃/apex:page>

    ReplyDelete
  19. In this advanced photoshop, I'll show you how to make cool action game posters. I hope you like it and thanks for watching!

    ReplyDelete