function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Rogerio Da SilvaRogerio Da Silva 

Get Session ID/Token in Lightning Component for Communities

Hi There,

We have a custom component in my Community Page and we are trying to get the Session Id or Access Token from the user who is logged in on Community Builder using Preview mode.

We have a code in place that works if the user is not in Preview Mode, basically we call an apex code and execute the UserInfo.getSessionId(), it returns the sessionid and I can do a rest call with this session ID. 
This SessionID works just when the user publishes a page and access it using the public URL. When I get the SessionID inside of Community Builder and click on Preview, and try to do a rest call with the session ID, it gives me an Invalid Session.

The link below is the link that I access my page and I can get the SessionId and do a rest call with no issue.
https://xxxdeveloper-edition.na50.force.com/CMSite/s/

The link below is when I am on Community Builder - Preview Mode, in this case I get the SessionID, but I cannot do a REST call.
https://xxxdev-ed--sitepreview.na50.force.com/CMSite/s/

said all that I have two questions.

1 - Why this Session Id in Preview mode is invalid, but the same code when I am using public link it works just fine?

2 - Is there another way to obtain the SessionId where I can do a Rest Call using Lightning component in Community Builder?

Please, let me know if you need any further information.
Thank you in advance.
NagendraNagendra (Salesforce Developers) 
Hi Rogerio,

1.- The session is related with the domain. Because of this the session is invalid in preview

2.- The best option is to get access token again. You can see how here(https://spaindevelop.wordpress.com/2017/08/05/usando-salesforce-tooling-api-salesforce-rest-api/) (sorry but is Spanish)

Hope this helps.

Please mark this as solved if it's resolved.

Thanks,
Nagendra
Rogerio Da SilvaRogerio Da Silva
Hi Nagendra, Thanks for answering me, I thought that too, where the session id is related with domain, but sf has a configuration where it allows you to use the session ID in different domain. I enabled that and still not working. If I do a test using the Valid Refresh Token in two different domains it works fine. which means that the session id for different domain is working, if the session id is valid. Your second option, I can't do that because this process needs username and password, and in my case I am in Community where the user has done that already and I need to use his/her session. 

Here are the two domains that I tested.
https://xxx-dev-ed.my.salesforce.com
https://xxx-developer-edition.na50.force.com/sfsites/c