본문 바로가기

개발자정보

Lightning Context 현재 사용자의 세션 ID를 가져오는 방법

반응형

The session id can be fetch through UserInfo.getSessionId() method in apex but which is not available lightning context. Named credentials and connected apps can be used to connect with external web services and internal salesforce api’s with Salesforce. This would requires more configurational effort and changes should be align with each deployments with respect to the orgs.

Here, I would like to share you a work around to solve this issue by using a custom visual force page and an apex controller.

  <apex:page controller="LexSessionController">
  Start{!$Api.Session_ID}End
  </apex:page>

 

  public class LexSessionController {
   
  public static String fetchUserSessionId(){
  String sessionId = '';
  // Refer to the Page
  PageReference sessionIdPage = Page.LexGetSessionIdPage;
  // Get the content of the VF page
  String vfContent = sessionIdPage.getContent().toString();
  // Find the position of Start and End
  Integer startPosition = vfContent.indexOf('Start') + 'Start'.length(),
  endPosition = vfContent.indexOf('End');
  // Get the Session Id
  sessionId = vfContent.substring(startPosition, endPosition);
  System.debug('sessionId '+sessionId);
  // Return Session Id
  return sessionId;
  }
  }
String sessionId =  LexSessionController.fetchUserSessionId();

This expression {!$Api.Session_ID} provides the session id of the current user in the VF page, which is extracted in the apex controller. the below code snippet helps to get the session id in the lightning context (AuraEnabled methods).

반응형