Named credentials using OAuth

Sometimes you need to use the Rest API in your Apex Code to make callouts to other Salesforce Orgs or even to the same Org where you are executing your code.
You could use Named Credentials to avoid storing user and password credentials (normally in an unsecure way) with OAuth.

We will need the following components for achieving our goal:

  • Connected App
  • Auth Provider
  • Named credentials

Let’s see an example of set up;

Code for testing:

public class HTTPRequestNamedCredentialsOauth {

public static void makeCallout() {

HttpRequest req = new HttpRequest();
Http http = new Http();
String baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
req.setHeader('Authorization', 'OAuth {!$Credential.OAuthToken}');

try {
HttpResponse response = http.send(req);

if ( response.getStatusCode() != 200 ) {
System.debug('Error response: ' + response.getBody());
} else {
System.debug('Successful response: ' + response.getBody());

catch( exception ex){
system.debug('Exception caught: ' + ex.getMessage());



Let’s call our code:

And see the output:

Leave a Reply

Notify of