• Syed Sajjad 20
  • NEWBIE
  • 0 Points
  • Member since 2020

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies
I am trying to understand how to set up the Named Credentials & OAuth Provider in Salesforce for calling the External REST API. Before setting this up I tested the call to the REST API through Apex like and it works fine
public class TestD365API {
    public final String clientId = 'xxxxxxx';
    public final String clientSecret = 'xxxxxx';
    public final String tenant_id = 'xxxx';
    public final String resource = 'https://abc.dynamics.com';

    public String getD365Customer(){             
        String reqbody = 'grant_type=client_credentials&client_id='+clientId+'&client_secret='+clientSecret+'&tenant_id='+tenant_id+'&resource='+resource;
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setBody(reqbody);
        req.setMethod('POST');
        req.setEndpoint('https://login.microsoftonline.com/tenant/oauth2/token');
        HttpResponse res = h.send(req);
        deserializeResponse resp1 = (deserializeResponse)JSON.deserialize(res.getbody(),deserializeResponse.class);
        String atoken = resp1.access_token;
        System.debug('Access Token=========' + atoken);

        Http http1 = new Http();
        HttpRequest req1 = new HttpRequest();
        req1.setEndpoint('https://abc.dynamics.com/data/Customers');
        req1.setMethod('GET');
        req1.setHeader('Authorization','Bearer '+atoken);
        HttpResponse res1 = http1.send(req1);
        System.debug('Response Body=========' + res1.getBody());
        return res1.getBody();                
    }  

    public class deserializeResponse
    {
        public String token_type;
        public String expires_in;
        public String ext_expires_in;
        public String expires_on;
        public String not_before;
        public String resource;
        public String access_token;
    }
}
I am passing 5 parameters in the request body to get the bearer token from the Authorization Provider and passing the token to the Rest endpoint and retrieving the data back.
Now trying to use Named credentials instead like below
User-added imagewhere in the Authorize URL I am giving as https://login.microsoftonline.com/tenant/oauth2/authorize?grant_type=client_credentials&tenant_id=xxxxxxxxxxx
And changed my Apex Code like

User-added image​​​​​​​I am not sure how to pass all the parameters (grant_type,tenant_id, client_id,client_secret,resource) to the Auth Provider and the bearer token to the Rest API endpoint through Named Credentials and get the response back. I am sure this is not the firewall/issue on Client end as I am able to test it through Apex Code. Any help is appreciated.
 
  • February 14, 2020
  • Like
  • 0