[SalesForce] Using Named Credentials with OAuth 2.0 username & Password Authentication

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:

enter image description here

Best Answer

As long as the Connected App you're using allows the refresh_token scope, salesforce will explicitly handle your OAuth session, including refreshing expired access tokens. Make sure you specify the correct values in the Scope field when creating the Named Credential. Just follow the directions exactly as specified in the blog post you've linked, and you should be good to go. Note that once you've configured this correctly, there's no need to call /services/oauth2/token, because you'll automatically have your access token maintained for you.

Related Topic