I have a requirement to make a call to the Apex Wrapper Metadata API from a Lightning component. The issue I am facing is that there is currently no native support for acquiring a valid API session ID from an @AuraEnabled method in a Lightning component Apex controller.
The Lightning developer documentation states that a named credential can be used in order to bypass this security restriction. However, when I set up a named credential and then pass that named credential reference as the endpoint for the Metadata Service API, I am receiving the following error:
“FATAL_ERROR System.CalloutException: Web service callout failed: WebService returned a SOAP Fault: INVALID_SESSION_ID: This session is
not valid for use with the API faultcode=sf:INVALID_SESSION_ID
faultactor=”.I have found a potential work around using Visualforce. However, the thread presenting this work around does not reference the “Named Credentials” feature as an option.
This post also presents the same issue where the documented named credential stops have been followed and the same error is received, but no solution has yet been offered.
I am not able to understand why the named credential feature is not bypassing the session id security measure for Lightning components.
Any input would be greatly appreciated.
Answer
You have to manually replace the Session ID in your request body/header .
In named credentials we have options to use the Merge fields in header/body
@AuraEnabled
public static String getOrgLimits(){
HTTP http=new HTTP();
HTTPRequest hres=new HTTPRequest();
hres.setEndpoint('callout:OWNINSTANCE'+'/services/data/v39.0/limits');
hres.setMethod('GET');
hres.setHeader('Authorization','Bearer {!$Credential.OAuthToken}');//Magic happens here
HttpResponse response=http.send(hres);
System.debug(response.getBody());
return response.getBody();
}
In the above example I am trying to hit my own org’s REST endpoint to get LIMITS of my current org. Its native REST calls without using SESSION ID.
In case of SOAP callout you can code something like
public class EchoManager {
public String endpoint_x = 'callout:Echo_Service';
. . .
public String echo(String text) {
WSEchoManager.echo_element request_x = new WSEchoManager.echo_element();
request_x.text = text;
this.SessionHeader = new SessionHeader_element();
this.SessionHeader.sessionId = '{!$Credential.OAuthToken}';//Magic happens here
You have to use merge field header for Rest Call
where as you have to use Merge field Body in SOAP call.
You can read more about merge fields here
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_callouts_named_credentials_merge_fields.htm
https://blog.enree.co/2016/03/salesforce-apex-lets-play-with-named.html
Attribution
Source : Link , Question Author : Daniel Fuller , Answer Author : Robs