Accessing Apex rest class with OAuth 2.0 with Named Credential authentication mechanism

I have been trying to implement Oauth 2.0 in my org and my requirement is to use Named credentials only when making a apex callout. I am using Named credentials, Oauth, Connected Apps and auth. provider to establish a connection with an external Salesforce org. The external org has exposed an apex class as REST service that I am trying to access using my org. I have followed the steps given in this link to setup everything :

Below are the setting at my end:

  1. Connected App:enter image description here
  2. Auth Provider:enter image description here
  3. Named Credentials:enter image description here

I am trying to test hitting the service using the below code in execute anonymous. I used req.setHeader('Authorization', 'OAuth {!$Credential.OAuthToken}'); in the request header. On executing I get this error in response body – [{"message":"Session expired or invalid","errorCode":"INVALID_SESSION_ID"}].

Http http = new Http();
HttpRequest req = new HttpRequest();
req.setHeader('Authorization', 'OAuth {!$Credential.OAuthToken}'); 
String JSONString = '{"AccountNumber":"65764556","AccountName":"xyz"}]}';
HttpResponse res = http.send(req);    
System.debug('Response Body===========' + res.getBody()); //  `[{"message":"Session expired or invalid","errorCode":"INVALID_SESSION_ID"}]`

What am I missing here?


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Assuming your credentials are set up correctly – You are missing the path on your endpoint

  1. Edit and save your Named Credential to redo the oAuth process. If you can complete that then the Auth Provider is set up correctly
  2. Endpoint is not correct but would not product the invalid session id, it would be a different error

To validate that your named credential is at least working use it for the SF REST API

Http http = new Http();
HttpRequest req = new HttpRequest();
HttpResponse res = http.send(req);
System.debug('Response Body===========' + res.getBody());

Note As sfdxfoc pointed out: You’re using the Generate Authentication Header feature, so you shouldn’t be setting your own

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x