I am trying to access dashboard through dashboard API, If I run the following method through visualforce page,it works, but If I call it from lightning component, It gives error. and the detail response body is :

[{"message":"This session is not valid for use with the REST API","errorCode":"INVALID_SESSION_ID"}]'

please check the following method

    public static String GetDashboardData(String StrDashboardName) {


    Id dashboardId = SOQLHelper.GetDashboardId( StrDashboardName);
     HttpResponse res ;
    if(dashboardId != null){
        HttpRequest req = new HttpRequest();
        req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
        req.setHeader('Content-Type', 'application/json');

        Http h = new Http();
        res = h.send(req);

        while (res.getStatusCode() == 302) {
            res = new Http().send(req);    

         system.debug('res = -------------'+res);
         system.debug('res body----------- = '+res.getbody());
    return null;

It works in workbench rest explorer also.

please let me know what can be the reason that it is not working in lightning component.

Thanks in advance!

  • remove the 'bearer ' from req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID()); – keepler Feb 6 '18 at 10:13
  • removed but still getting same error. :( – Shilpa Feb 6 '18 at 10:25

Visualforce pages are synchronous, it persist the session Id but the lightning components does not persist the session Id.

So we need take the visualforce page session Id, in Rest API call when calling from lightning component.

please check the below code.

public static String getSessionIdFromVFPage(){
        PageReference visualforcePage = Page.SessionId;
        String content = visualforcePage.getContent().toString();
        Integer s = content.indexOf('Start_Of_Session_Id') + 'Start_Of_Session_Id'.length(),
                e = content.indexOf('End_Of_Session_Id');
        return content.substring(s, e);


<apex:page >


req.setHeader('Authorization', 'Bearer ' + getSessionIdFromVFPage());



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.