Question
I need to call the Apex Wrapper Metadata API from a Lightning component, but I am facing an issue where there is no native support for acquiring a valid API session ID from an @AuraEnabled method in an Apex controller.
Salesforce documentation suggests using a Named Credential to bypass this security restriction. However, when I set up a Named Credential and pass it as the endpoint for the Metadata Service API, I receive 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 came across a potential workaround using Visualforce, but the discussion did not reference Named Credentials as a viable solution. Other developers have reported similar issues where Named Credentials were set up correctly, yet the same INVALID_SESSION_ID error persisted, with no clear resolution.
Why is the Named Credential feature not bypassing the session ID security measure for Lightning components? How can I successfully make this API call? Are there any alternative approaches?
Answer
The INVALID_SESSION_ID error occurs because the session ID used within a Named Credential does not work for certain API calls, especially SOAP-based APIs like the Metadata API. Salesforce enforces security measures that prevent direct access to the session ID in an @AuraEnabled method. However, there are a few workarounds to resolve this issue:
1. Use Named Credentials with OAuthToken
Instead of relying on a session ID, you should use the {!$Credential.OAuthToken} merge field, which provides a valid authentication token when using Named Credentials.
For a REST API call, you can structure your Apex controller as follows:
@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');
// Use Named Credential OAuth Token instead of Session ID
hres.setHeader('Authorization', 'Bearer {!$Credential.OAuthToken}');
HttpResponse response = http.send(hres);
System.debug(response.getBody());
return response.getBody();
}This method calls the Salesforce REST API to fetch organization limits without using a session ID. The key part is the OAuthToken merge field, which provides valid authentication.
2. SOAP API Call Using Merge Field in the Request Body
For a SOAP API call, instead of passing the token in the header, you need to include it in the request body. Here’s an example:
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;
// Use OAuthToken in the session header
this.SessionHeader = new SessionHeader_element();
this.SessionHeader.sessionId = '{!$Credential.OAuthToken}';
return someSoapCall(request_x);
}
}For SOAP callouts, the merge field must be used inside the request body instead of the header. This ensures that the Named Credential is properly utilized without causing authentication errors.
3. Alternative: Use a Connected App with OAuth Flow
If Named Credentials are not working, another approach is to set up a Connected App and use OAuth 2.0 for authentication. This involves:
- Creating a Connected App in Salesforce.
- Configuring OAuth settings and getting the Consumer Key & Secret.
- Using the OAuth 2.0 Username-Password Flow to obtain an access token.
- Making the API call with the retrieved access token.
This method provides greater flexibility, but it requires additional setup.
The best approach depends on your use case:
- If using a REST API, pass
{!$Credential.OAuthToken}in the Authorization header. - If making a SOAP API call, include
{!$Credential.OAuthToken}in the request body instead of the header. - If Named Credentials are not working, consider using a Connected App with OAuth 2.0 for authentication.
By implementing these solutions, you can successfully call the Salesforce API from a Lightning Component without encountering session ID restrictions.
Kick Start Your Journey with Real-Time Project-Based Salesforce Learning
Our Salesforce course is designed to give you a comprehensive understanding of the Salesforce platform, equipping you with the essential skills needed to excel in the CRM industry. The curriculum covers key modules such as Salesforce Admin, Developer, and AI, combining theoretical learning with hands-on experience. Through real-world projects and practical exercises, you will develop the expertise to solve complex business challenges using Salesforce solutions. Our experienced instructors ensure you gain both technical proficiency and industry-relevant insights to succeed in the Salesforce ecosystem.
In addition to technical training, our Salesforce training in India offers personalized mentoring, certification support, and interview coaching to enhance your career prospects. You’ll have access to extensive study materials, hands-on project work, and continuous guidance throughout your learning journey. By the end of the program, you’ll be fully prepared for certification exams and equipped with the problem-solving skills that employers value. Take the first step toward a successful Salesforce career and unlock new opportunities. Sign up for a free demo today!



Leave a Reply
You must be logged in to post a comment.