How to Get the Session Id of Current User in Lightning Web Component

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

Step 2: Create a Helper Class

Step 3: Use this Helper Class in any Apex Class to get session Id 

That's all for today! Hope you like this blog. This is how we can current user session Id in @AuraEnabled method when calling from LWC. Still, if you have any further suggestions, thoughts, and questions, then just make sure to comment down.

Thank You!

Comments