I created a new connected apps and obtained the Client secret and Id. I am trying to make a login call to another Salesforce org to obtain the access token. Below approach was successful:
String endpoint='https://test.salesforce.com/services/oauth2/token';
String username = 'username';
String password = 'password';
String ClientId= 'abcdefgh';
String ClientSecret = 'xyz234890';
Httprequest req = new HttpRequest();
req.setMethod('POST');
req.setHeader('Content-Type','application/x-www-form-urlencoded');
req.setBody('grant_type=password' +
'&client_id=' + ClientId +
'&client_secret=' + ClientSecret +
'&username=' + username +
'&password=' + password
);
req.setEndpoint(endpoint);
Http http = new Http();
HttpResponse res;
try {
res = http.send(req);
system.debug('body:'+res.getBody());
}catch(system.CalloutException e){
system.debug('error'+e);
}
In response I get the access token. However I want to try obtaining the access token using named credentials as I do not want to hard code the username,password end points in the apex code. I cam across this article to use Named credentials with OAuth 2 - http://www.jitendrazaa.com/blog/salesforce/salesforce-to-salesforce-integration-using-named-credentials-in-just-5-lines-of-code/ .
Any suggestion whether the above approach would give me the access token in response that I can use in subsequent callouts?
Screen shot of auth provider: