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?
Answers:
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
- Edit and save your Named Credential to redo the oAuth process. If you can complete that then the Auth Provider is set up correctly
-
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
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0