[SalesForce] 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 :

http://manueltejeiro.com/2016/05/12/named-credentials-using-oauth/

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.setEndpoint('callout:NamedCredtional_name');
req.setHeader('Content-Type','application/json'); 
req.setHeader('Authorization', 'OAuth {!$Credential.OAuthToken}'); 
req.setMethod('POST');
req.setTimeout(30000);
String JSONString = '{"AccountNumber":"65764556","AccountName":"xyz"}]}';
req.setBody(JSONString);
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?

Best Answer

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

    req.setEndpoint('callout:NamedCredtional_name/services/apexrest/{YOURRETREQUESTNAMEHERE}');
    

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();
req.setEndpoint('callout:NamedCredtional_name/services/data/v36.0');
req.setMethod('GET');
req.setTimeout(30000);
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