Getting Session ID in Lightning

So, as it turns outs there is no way of getting a valid API-capable Session Id from lightning component, here is a quote from the partner discussion forums:

Three things:

  1. There's no $Api global variable in Lightning Components today. So, {! $Api.whatever } will always fail.

  2. This is intentional at this time. There's no official/supported way to get an API-capable session ID in Lightning Components. Again, this is by design.

  3. With only a little creativity and cleverness you can create a bare-bones Visualforce page with {! $Api.SessionID }, and then call getContent(thatPage) from Apex to get a page that contains an API-capable session ID, which you should be able to parse out easily enough.

From there, it's not hard to pass that session ID along to Lightning Components via an @AuraEnabled method.

But let's be clear: this is a hack, the performance will be poor, and there's good reasons to keep an API-capable session ID out of your Lightning Components code.

So, I ended-up building the not recommended hack as a workaround for this to work in Lightning.

Just create a simple Visualforce Page as:


And then get the Session Id with the visualforce_Page.getContent() method, something like:

public static MetadataService.MetadataPort createService()
    MetadataService.MetadataPort service = new MetadataService.MetadataPort();
    service.SessionHeader = new MetadataService.SessionHeader_element();
    //service.SessionHeader.sessionId = UserInfo.getSessionId();
    service.SessionHeader.sessionId = Utils.getSessionIdFromVFPage(Page.SessionId);
    return service;


global class Utils {
    global static String getSessionIdFromVFPage(PageReference visualforcePage){
        String content = visualforcePage.getContent().toString();
        Integer s = content.indexOf('Start_Of_Session_Id') + 'Start_Of_Session_Id'.length(),
                e = content.indexOf('End_Of_Session_Id');
        return content.substring(s, e);

And then you got a valid session id to work with.

According to the known issue Summer'17- Generating a Session Id from Lightning Domain Provides Invalid Session Id (W-3981698) it should be possible to pass UserInfo.getSessionId() out to lightning component via an @AuraEnabled an use it for API calls.

This should be possible from Winter '18 onward.