When you are calling the apex method from LWC and doing callouts using the same org, we used UserInfo.getSessionId() to get the current user session Id for authorization but while running it from Lightning Web Component you will get,
System.HttpResponse[Status=Unauthorized, StatusCode=401]
But when you run the code from Anonymous Window, you will receive
System.HttpResponse[Status=OK, StatusCode=200]
Also Read: How to create a Reusable Custom Lookup Search Component in Lightning Web Component
So, How you can get a session Id when calling Apex from Lightning Web Component? There is a hack to get the session id in apex. We need to create a Visualforce Page to get the session Id.
Step 1: Create a Visualforce Page
<apex:page > | |
<div id="SessionId">{!GETSESSIONID()}</div> | |
</apex:page> |
Step 2: Create a Helper Class
public class SessionIdHelper | |
{ | |
public static String getCurrentUserSessionId() | |
{ | |
PageReference pg = Page.SessionId; | |
Blob b = pg.getContent(); | |
String htmlBody = b.toString(); | |
htmlBody = htmlBody.split('<div id="SessionId">')[1]; | |
htmlBody = htmlBody.split('</div>')[0]; | |
System.debug('htmlBody ::::::' + htmlBody); | |
return htmlBody; | |
} | |
} |
Step 3: Use this Helper Class in any Apex Class to get session Id
public with sharing class getSessionIdController { | |
@AuraEnabled | |
public static string getSessionId(){ | |
String sessionId = SessionIdHelper.getCurrentUserSessionId(); | |
return sessionId; | |
} | |
} |
Thank You!
Comments