Using Visualforce to securely retrieve session IDs for API calls
In Salesforce Lightning, retrieving the Session ID within an LWC or Aura Component isn't straightforward. Here's a secure solution using Visualforce.
UserInfo.getSessionId() returns null in Lightning Context, blocking these scenarios:
// Returns null in Lightning
String sessionId = UserInfo.getSessionId();
Visualforce pages run in Classic context, allowing access to {!$Api.Session_ID}.
<!-- SessionIdVF.page -->
<apex:page>
Start_Of_Session_Id{!$Api.Session_ID}End_Of_Session_Id
</apex:page>
// FetchSessionId.cls
public class FetchSessionId {
public static String apiEnabledSessionId() {
PageReference sessionPage = Page.SessionIdVF;
String vfContent = sessionPage.getContent().toString();
Integer startIndex = vfContent.indexOf('Start_Of_Session_Id') + 'Start_Of_Session_Id'.length();
Integer endIndex = vfContent.indexOf('End_Of_Session_Id');
return vfContent.substring(startIndex, endIndex);
}
}
// In your Aura/LWC controller
getSessionId() {
return new Promise((resolve, reject) => {
const sessionId = FetchSessionId.apiEnabledSessionId();
if(sessionId) {
resolve(sessionId);
} else {
reject('Failed to get session ID');
}
});
}
For pure LWC solutions, consider using: