Hello Everyone, In today's post we are going to see a code example that helps you to get current logged-in user session id in lightning context. This will help you to pass user session id in REST api's that execute through lightning components. So let's begin,
Session Id of Logged-in User in Lightning Context
In Salesforce, Session id can be fetched through UserInfo.getSessionId() function in apex but unfortunately this is not available in lightning context. Mainly we used session id to call salesforce rest api's. Here, I would like to shre you a work around to solve this issue by using some custom coding that includes a visualforce page and an apex controller.
1. Navigate to Developer Console | File | New | Visualforce Page and create a new visualforce page named UserSessionPage and replace the following code.
Visualforce Page:
<apex:page controller="UserSessionHandler">
Start{!$Api.Session_ID}End
</apex:page>
2. Navigate to Developer Console | File | New | Apex Class and create a new apex class named UserSessionHandler and replace the following code.
Apex Class:
public class UserSessionHandler {Sample Code Example:
public static String fetchUserSessionId(){
String sSessionId = '';
PageReference sessionIdPage = Page.UserSessionPage;
// 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();
Integer endPosition = vfContent.indexOf('End');
// Get the Session Id
sSessionId = vfContent.substring(startPosition, endPosition);
System.debug('sessionId '+sSessionId);
// Return Session Id
return sSessionId;
}
}
HttpRequest req = new HttpRequest();
req.setEndpoint('//enpoint');
req.setMethod('GET');
String auth = 'Bearer '+UserSessionHandler.fetchUserSessionId();
req.setHeader('Authorization', auth);
//Hold Response in HTTP response
Http http = new Http();
HTTPresponse res= http.send(req);
String response = res.getBody();
Note:Remember this trick will work only lightning context for classic you can go for Userinfo.getSessionId() function.
Session Id looks like below image.
Hope you like this post, for any feedback or suggestions please feel free to comment. I would appreciate your feedback and suggestions.Thank you.
0 Comments
Post a Comment