0

I am integrating Google Drive API with salesforce. I have created 2 classes here, one is the controller class for the page and another one is helper class. As soon as my page gets loaded I can see access token(after entering the crendials) in debug log but, when I click on a disp button then it gets nulled. I dont understand why is this happening and how to resolve it.(My AccessToken in GDrive class is null too.) Following is my code:

Controller code:

    public class GDrive {
        public static String AccessToken;

        public GDrive(){
            System.debug('GDrive constructor called ');
        }

        public PageReference authentication(){
            System.debug('Authentication called');
            PageReference pg = GoogleDriveHelper.DriveAuth();
            return pg;
        }

        public void Files(){
            System.debug('Gdrive access token in gd is '+GDrive.AccessToken);
            System.debug('Files called in GDrive');
            //GoogleDriveHelper.AccessToken();
            //list<String> fList = new list<String>();
            /*String fList = GoogleDriveHelper.displayFiles();
            System.debug('>>> l is ' + fList);
            //return fList;*/
        }
    }

Helper class code:

public class GoogleDriveHelper {
    // Stores authorization code.
    private static String code;
    //Client ID.
    private static string key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com';
    //Client secret key.
    private static string secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx';
    // Url to be redirected when authentication is done.
    private static string redirect_uri = 'https://c.ap5.visual.force.com/apex/googleDrive';
    private static String access_token;
    public static list<String> files;
    public GoogleDriveHelper()
    {
        System.debug('Constructor of Helper class called ');
        /*code = ApexPages.currentPage().getParameters().get('code');
        System.debug('constructor for helper class called');

        Get the access token once we have code
        if(code != '' && code != null)
        {
            AccessToken() ;
        }*/
    }

    public static PageReference DriveAuth()
    {
        //Authorization
        code = ApexPages.currentPage().getParameters().get('code');
        if(code != '' && code != null){
            System.debug('<<>>>><');
            GDrive.AccessToken = GoogleDriveHelper.AccessToken();
            System.debug('GDrive.AccessToken is '+GDrive.AccessToken);
            return null;
        }
        else{
            PageReference pg = new PageReference(GoogleDriveAuthUri (key , redirect_uri)) ;
            return pg;
        }

    }

    // To redirect to OAuth server, google drive api here.
    public static String GoogleDriveAuthUri(String Clientkey,String redirect_uri)
    {
        System.debug('Entered authorization ');
        String key = EncodingUtil.urlEncode(Clientkey,'UTF-8');
        String uri = EncodingUtil.urlEncode(redirect_uri,'UTF-8');
        String authuri = '';
        // Call the Google OAuth 2.0 endpoint directly, you'll generate a URL and set the parameters on that URL.
        authuri = 'https://accounts.google.com/o/oauth2/auth?'+
        'client_id='+key+
        '&response_type=code'+
        '&scope=https://www.googleapis.com/auth/drive'+ //Scope to access data on drive. This gives full access
        '&redirect_uri='+uri+
        '&state=security_token%3D138r5719ru3e1%26url%3Dhttps://oa2cb.example.com/myHome&'+
        //'&login_hint=jsmith@example.com&'+
        'access_type=offline';  //Indicates whether your application can refresh access tokens when the user is not present at the browse
        return authuri;
    }


    public static String AccessToken()
    {
        code = ApexPages.currentPage().getParameters().get('code');
        //Getting access token from google drive api app
        System.debug('code in access_token is ' + code);
        HttpRequest req = new HttpRequest();
        req.setMethod('POST');  //http method of POST is used.
        req.setEndpoint('https://accounts.google.com/o/oauth2/token');  //URL from which you have to extract resources.
        req.setHeader('content-type', 'application/x-www-form-urlencoded'); //file type:application, extension: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);    //Time out is for 60 secs.

        Http h = new Http();
        String resp;
        HttpResponse res = h.send(req);
        System.debug('access token request is ' + res);
        resp = res.getBody();
        Map<String,object> m = (Map<String, Object>)Json.deserializeuntyped(resp);  // Stores JSON string values in a map
        access_token = (String)(m.get('access_token')); //Retrives the value of access token from map and stores it.
        //We have to pass this access token everytime when a hit is made.
        System.debug(' access Token is ' + access_token);
        return access_token;

    }

    public static String displayFiles(){
        System.debug('access_token is >>>> '+ access_token);
        HttpRequest req = new HttpRequest();
        req.setMethod('GET');   // Http method of get is used here.
        // setEndPoint url parameters are passed 
        req.setEndpoint('https://www.googleapis.com/drive/v3/files?corpora=user,allTeamDrives&includeTeamDriveItems=true&supportsTeamDrives=true');
        // to pass access token.
        System.debug('AccessToken in disp is ' + access_token);
        req.setHeader('Authorization', 'Bearer ' + access_token);
        req.setTimeout(60*1000);

        Http h = new Http();
        String resp;
        HttpResponse res = h.send(req);
        System.debug('Send request is ' + res);
        resp = res.getBody();   // JSON string values are returned here.
        Map<String,object> m = (Map<String, Object>)Json.deserializeuntyped(resp);
        System.debug(m.size());
        String str = (String)m.get('files.Name');
        //files = str.split(',');
        //System.debug('?????? '+files[0]);
        System.debug(resp);
        return str;
    }
}

There are 3 logs generated and they are as : First debug log:

USER_DEBUG [5]|DEBUG|GDrive constructor called 
USER_DEBUG [9]|DEBUG|Authentication called
USER_DEBUG [45]|DEBUG|Entered authorization

Second debug log:

USER_DEBUG [5]|DEBUG|GDrive constructor called 
 USER_DEBUG [9]|DEBUG|Authentication called
 USER_DEBUG [30]|DEBUG|<<>>>><
 USER_DEBUG [66]|DEBUG|code in access_token is 4/Axxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx50v9eZJpuV7Fs-zaYU
 USER_DEBUG [79]|DEBUG|access token request is System.HttpResponse[Status=OK, StatusCode=200]
 USER_DEBUG [84]|DEBUG| access Token is xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxjG0WMZLN_DylUQnuwfDtB_BtjttyNfio4XhTHPA
 USER_DEBUG [32]|DEBUG|GDrive.AccessToken is xxxxxxxxxxxxxxxxxxxxxxxxxxxjG0WMZLN_DylUQnuwfDtB_BtjttyNfio4XhTHPA

Third debug log is:

  USER_DEBUG [15]|DEBUG|Gdrive access token in gd is null
  USER_DEBUG [16]|DEBUG|Files called in GDrive
  • do you have any verbatim error messages/debug logs? for example, line where the error produces itself? – glls May 30 '18 at 19:24
  • If you don't want to build it from scratch, have you looked into the native support via Files Connect to Google Drive? – Mark Pond May 30 '18 at 19:34
  • Can't say for certain if this is the case here, but when you try to system.debug() an access token for another Salesforce org, Salesforce will refuse to print the access token to the log for security reasons. Error messages from your callout(s) are going to be more helpful here. – Derek F May 30 '18 at 19:38
  • I have edited for the debug only debug logs here, please go through them – Krishnan Mishra May 30 '18 at 19:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.