Sunday, 4 May 2014

Twitter Application-only authentication in Salesforce Apex

Hello all,

Today I will be posting an example on how to implement the Twitter Application-only authentication using Salesforce Apex.

Overview


The Twitter Application-only authentication is used when no user sign-in with Twitter is required.
When using this type of authentication, we are allowed to call limited Twitter functionalities, namely :


  • Pull user timelines;
  • Access friends and followers of any account;
  • Access lists resources;
  • Search in tweets;
  • Retrieve any user information;

  • In our example, we will be implementing the Authentication flow described in Twitter Application-only authentication which involves two HTTP requests.

    Code


     public TwitterContr(){  
          HttpRequest req = new HttpRequest();  
          req.setMethod('POST');  
          req.setEndpoint('https://api.twitter.com/oauth2/token');  
            
          //// Step 1: Encode consumer key and secret  
            
          String consumerKey = 'xvz1evFS4wEEPTGEFPHBog';  
          String consumerSecret = 'L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg';  
            
          Blob headerValue = Blob.valueOf(consumerKey + ':' + consumerSecret);  
          String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);  
         
          //// Step 2: Obtain a bearer token  
                 
          req.setHeader('Authorization', authorizationHeader);  
          req.setHeader('Content-Type','application/x-www-form-urlencoded;charset=UTF-8');  
          req.setBody('grant_type=client_credentials');  
         
          // Create a new http object to send the request object  
          // A response object is generated as a result of the request  
          // the server will respond with a JSON-encoded payload  
         
          Http http = new Http();  
          HTTPResponse res = http.send(req);  
          
          String jsonStr = res.getbody();  
          JSONParser parser = JSON.createParser(jsonStr);  
            
          // extract access token from JSON response  
          string accessToken;  
          while (parser.nextToken() != null) {  
               if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'access_token')) {  
                    // Get the value.  
                    parser.nextToken();  
                    accessToken = parser.getText();  
               }  
          }  
         
          // access token can now be used to perform other requests  
          //// Step 3: Authenticate API requests with the bearer/access token  
            
          // e.g. searching for tweets   
            
          HttpRequest req1 = new HttpRequest();  
          req1.setMethod('GET');  
          req1.setEndpoint('https://api.twitter.com/1.1/search/tweets.json?q=%23freebandnames');  
         
          String authorizationHeader1 = 'Bearer ' + accessToken;  
          req1.setHeader('Authorization', authorizationHeader1);  
         
          Http http1 = new Http();  
          HTTPResponse searchResponse = http.send(req1);  
          system.debug('## body1 : ' + searchResponse.getBody());  
     }  
    

    Cheers!!

    No comments:

    Post a Comment