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:
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?