Developer Note: How to Get the SessionId to Use When Calling from An Action Back to Salesforce

All API calls into Salesforce endpoints require an authorization. Generally, the SessionId will suffice for this, allowing you to avoid having to set up Auth Providers and Named Credentials just to make an API call to your own org. However, for security reasons, it’s tricky to get the SessionId from Apex.

I’m not sure why the following mechanism works, when all other mechanisms do not work, but I believe this mechanism is here to stay.

First, I’ll give you the most direct way to use this solution.

Method 1: Use FlowActionsBasePack

  1. Install FlowActionsBasePack.
  2. In your Apex invocable action, add the following code:
String sessionId = Test.isRunningTest() ? 'TEST_SESSION_ID' : Page.usf3__GenerateSessionIdForLWC.getContent().toString();

You can then use the sessionID in your outbound HTTP Request:

 HttpRequest req = new HttpRequest();
req.setHeader('Content-Type', 'application/json');
req.setHeader('Authorization', 'Bearer ' + sessionId); 
req.setHeader('Accept-Encoding', 'gzip, deflate, br');
req.setHeader('Accept', '*/*');

Method 2: Add a Visualforce Page to your org

FlowActionsBasePack isn’t actually doing much work here, and you don’t need to use it; you can simply replicate what it does. To do that you have to first understand what’s really going on.

If you look at the line of code, you can see that the main function is a call to Page.usf3__GenerateSessionIdForLWC

As you can see in this screen shot of FlowActionsBasePack, ‘GenerateSessionIdForLWC’ is a tiny Visualforce page:

It took a surprising amount of web searching to find documentation on using ‘Page’ in Apex. I finally found it here. Page is used to instantiate a PageReference, which is how Apex interacts with Visualforce pages. ‘usf3__’ is the namespace used by all the code in FlowActionsBasePack. So our code basically calls getContent() on the page you can see in the image above. And the only content on the page is a reference to the SessionID.

So, another way you can attack this problem is to create your own Visualforce page on your org. You could name it GenerateSessionIdforLWC but of course you don’t need to. Use the <apex:page> block as shown above and save your page. From then on, any of your apex code can get the SessionId with a single line of code.