function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Ken Koellner 8Ken Koellner 8 

outbound oauth example

When searching the documentation for information on oauth, I find lots of information on other applications calling into salesforce to get access to SF.  Unfortunately, that's not the task I need to perform.  I need to, from salesforce, get access to another application.

I'm wondering if anyone knows of any good examples or tutorials for outbound authorization to other applications.

I think there may be ways to get help doing it with Per User Named Credentials but I would really like to see some examples of how to configure and code it.
Om PrakashOm Prakash
Hi Ken,
Outbound authorization to third party applications depends on their API, which authentication method they are providing, Basic or Oauth Flow.
Every application provider give us API doc which explain their flow of supported authentication.

I have just created a sample VF page and Apex class which demonstrate you outbond API authentication with Twitter and reterive latest tweets from official twitter handler of @Salesforce.

You need to create a sample APP on twitter (https://apps.twitter.com) , then replace the consumer key and consumer secret in my class variable with your own app's value.
 
public with sharing class TwitterOauth2Demo {
    /*
      This class is created for authentication demo with Twitter and get latest tweet from Salesforce.
      Author : Om Prakash
      CreatedDate : 24/03/2018
     */

    private String consumerKey = 'Consumer_KEY'; //From Twitter App > Application Settings > Consumer Key (API Key)
    private String consumerSecret = 'Consumer_secret '; // From Twitter App > Application Settings  > Consumer Secret (API Secret)
    public String generatedToken {set; get;}
    public String twitterTimelineResponse {set; get;}
    public String errorMessage {set; get;}
    
    // Method for get access Token from twitter. 
    public void getTokenFromTwitter() {
        try{
            String consumerKeyEncoded = EncodingUtil.urlEncode(consumerKey, 'UTF-8');
            String consumerSecretEncoded = EncodingUtil.urlEncode(consumerSecret, 'UTF-8');
            String ketTokenCombined = consumerKeyEncoded + ':' + consumerSecretEncoded;
            HttpRequest objReq = new HttpRequest();
            objReq.setEndpoint('https://api.twitter.com/oauth2/token');
            objReq.setMethod('POST');
            String authHeadParam = 'Basic ' + EncodingUtil.base64Encode(Blob.valueOf(ketTokenCombined));
            objReq.setHeader('Authorization', authHeadParam);
            objReq.setBody('grant_type=client_credentials');
            Http objHttp = new Http();
            HTTPResponse objRes = objHttp.send(objReq);
            System.debug('----response :'+ objRes.getBody());
            JSONParser objParse = JSON.createParser(objRes.getBody());
            while (objParse.nextToken() != null) 
            {
                if (objParse.getCurrentToken() == JSONToken.FIELD_NAME && objParse.getText() == 'access_token')
                {
                    objParse.nextToken();
                    generatedToken = objParse.getText();
                }
            }
         }
         catch(Exception ex)
         {  errorMessage = ex.getMessage();
            System.debug('Exception :' + ex.getMessage());
         }
    }
    // Returns the most recent Tweets from https://twitter.com/salesforce
    public void getTweetTimelines() {
        getTokenFromTwitter(); // Generate new access token before calling bellow API
        if(generatedToken == null ) {
            twitterTimelineResponse = 'Error while generating token, so unable to get messages. Check your debug log.';
            return;
        }
        try{
            HttpRequest objReq = new HttpRequest();
            objReq.setEndpoint('https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=salesforce');
            objReq.setMethod('GET');
            objReq.setHeader('Authorization', 'Bearer ' + generatedToken);
            Http objHttp = new Http();
            HTTPResponse objRes = objHttp.send(objReq);
            twitterTimelineResponse = objRes.getBody();
            if(String.isBlank(twitterTimelineResponse)){
                twitterTimelineResponse = objRes.toString();
            }
            System.debug('----response :'+ twitterTimelineResponse);
            // Put Your JSON Parsing Logic Here for twitterTimelineResponse
         }
         catch(Exception ex)
         {  errorMessage = ex.getMessage();
            System.debug('Exception :' + ex.getMessage());
         }
    }  
 }
<apex:page sidebar="false" showHeader="false" controller="TwitterOauth2Demo">
    <apex:form id="FormId">
        <p/>
        <apex:commandButton action="{!getTokenFromTwitter}" value="Genertae Access Token" rerender="resultSection"/> 
        <apex:commandButton action="{!getTweetTimelines}" value="Get Twitter Timeline" rerender="resultSection"/> 
        <p/>
        <apex:outputPanel id="resultSection">
            Token : {!generatedToken} <p/>
            Error Message : {!errorMessage} <p/>
            Twitter TimeLine JSON : <br/> {!twitterTimelineResponse } <br/>
        </apex:outputPanel>
    </apex:form>
</apex:page>

Doc reference for Twitter API which I have used in above code:
Create Twitter APP:   https://developer.twitter.com/en/docs/basics/authentication/guides/access-tokens
Generate OAuth 2 Bearer Token: https://developer.twitter.com/en/docs/basics/authentication/api-reference/token
Get Tweet timelines:  https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-mentions_timeline.html