+ 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() {
            String consumerKeyEncoded = EncodingUtil.urlEncode(consumerKey, 'UTF-8');
            String consumerSecretEncoded = EncodingUtil.urlEncode(consumerSecret, 'UTF-8');
            String ketTokenCombined = consumerKeyEncoded + ':' + consumerSecretEncoded;
            HttpRequest objReq = new HttpRequest();
            String authHeadParam = 'Basic ' + EncodingUtil.base64Encode(Blob.valueOf(ketTokenCombined));
            objReq.setHeader('Authorization', authHeadParam);
            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')
                    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.';
            HttpRequest objReq = new HttpRequest();
            objReq.setHeader('Authorization', 'Bearer ' + generatedToken);
            Http objHttp = new Http();
            HTTPResponse objRes = objHttp.send(objReq);
            twitterTimelineResponse = objRes.getBody();
                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">
        <apex:commandButton action="{!getTokenFromTwitter}" value="Genertae Access Token" rerender="resultSection"/> 
        <apex:commandButton action="{!getTweetTimelines}" value="Get Twitter Timeline" rerender="resultSection"/> 
        <apex:outputPanel id="resultSection">
            Token : {!generatedToken} <p/>
            Error Message : {!errorMessage} <p/>
            Twitter TimeLine JSON : <br/> {!twitterTimelineResponse } <br/>

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