How to call Rest Service using OAuth REST API ?

We created a REST Service in Salesforce in our previous blog, and now we want to call the REST service from another application. Salesforce DO NOT allow using Basic Authentication (Username & Password) for incoming REST calls. This is still true even if you are calling from another Salesforce instance.  We have to use OAuth to authenticate to Salesforce.

OAuth (Open Authorization) is an open protocol to provide secured authorization. Here are the list of OAuth flows used while making REST API calls:

In this blog, we are using Username-password flow to make a call to a REST Service in Salesforce using OAuth. Please follow the steps below to set up the REST call:

1) Remote Site Settings

First you need to create two entries in remote site settings:

  1. Enter the remote site Name, URL for Salesforce login https://login.salesforce.comremotesite.png
  2. Create another remote site Name, URL for accessing Salesforce data https://instance.salesforce.com.

2) Create Connected App

Now we create a Connected App:

  1. Go to Setup | Create | Apps.
  2. Under Connected App, Click “New”.
  3. Enter the name of Connected App and specify details as mentioned (in Screenshot) below.
  4. Click Save.

connectedap.png

Once you have created the Connected App, you will see the following screen with “Consumer Key” and “Consumer Secret”:

connectedAppSaved.png

 

We can use the “Consumer Key” which will be a client_id and “Consumer Secret” as client_secret inside the body of the call to make the callout.

grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password

Apex Code:-

/* Class for getting account record from other salesforce org through rest api integration
by calling class and its method from other org*/

public class TestWebService{
    public TestWebService(){
                                //You will get "clientId","clientSecret" when creating connected app in salesforce
        String clientId = '3MVG9szVa2RxsqBYoWov5yC4I5MxFgDDe3.6Z1g__FlEYNOPY45vALm1kA5oCZuFkHYxCzm2A3SdSoxFpUNU3';
        String clientSecret = '7917982719268332943';

        //We can also store our username password in custom setting.
        String username='ajomon@apexcoder.com';//salesforce username 
        String password='*l2YzP2TxlvI';//EUe4eHjMxXb8UFco1SPcpsZL9';//salesforce password
        // Generating the Access Token
        HttpRequest req = new HttpRequest();
        req.setMethod('POST');
        req.setEndpoint('https://login.salesforce.com/services/oauth2/token');// this is the OAuth endpoint where this request will be hit
        req.setBody('grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password);
        
        Http http = new Http();
        HTTPResponse res = http.send(req);
        String str = res.getBody();
        wrapObj = (Wrapper)Json.deserialize(str,Wrapper.class);
        accessToken = wrapObj.access_token;
        instanceUrl = wrapObj.instance_url;
        methodGet();
    }
        
    // Retrieve the Contacts from the otehr org.
    public void methodGet(){
        HttpRequest req = new HttpRequest();
        req.setMethod('GET');
        //req.setEndpoint(wrapObj.instance_url+'/services/apexrest/Account/getAccountById?name=champaKAli');
        
        req.setEndpoint(wrapObj.instance_url+'/services/apexrest/AccountService');
        req.setHeader('Authorization', 'OAuth '+wrapObj.access_token);
        Http http = new Http();
        HTTPResponse res = http.send(req);
        
        System.debug('***Response***** ' + res.getBody());
        //---------------------Here ------------------
        /*JSONParser parser = JSON.createParser(res.getBody());
        do{
            parser.nextToken();
        }while(parser.hasCurrentToken() && !'records'.equals(parser.getCurrentName()));
            parser.nextToken();
        List<account> acc = (List<Account>) parser.readValueAs(List<Account>.class);*/
    }
    public Contact con {get;set;}
    public String s1 {get;set;}
    public String accessToken;
    public String instanceUrl;
    public Wrapper wrapObj{get;set;}
    // Wrapper Class to Store the value from the Jason.
    public class Wrapper{
        String id;
        String instance_url;
        String access_token;
        String issued_at;
        String signature;
    }
}

In the above code, we are using client_id and client_secret to authorize the external app.

We can also parse the response using parser classes.

We can execute the above code using developer console and print all the accounts in system.debug() :

TestWebService tw = new TestWebService();
tw.methodGet();

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s