[SalesForce] Salesforce REST API: Session expired or invalid: INVALID_SESSION_ID

Background

I am trying to access the Salesforce Reporting REST API.

public with sharing class SalesforceReportApi {

    private final static String REPORTS_RESOURCE = '/services/data/v44.0/analytics/reports/';

    private static HttpResponse execute(String method, String restResource) {

        HttpRequest request = new HttpRequest();

        request.setMethod(method);
        request.setEndpoint(endpoint + restResource);
        request.setTimeout(120000); // 2 Minutes

        request.setHeader('Accept', 'application/json');    
        request.setHeader('Content-Type',  'application/json'); 
        request.setHeader('Authorization', 'OAuth ' + UserInfo.getSessionID());       
        request.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
        request.setCompressed(false); 

        HttpResponse httpResponse = new Http().send(request);

        return httpResponse;
    }

    private static String endpoint {
        get { 
            return URL.getOrgDomainUrl().toExternalForm(); 
        }
    }

    public static MatrixReport getMatrixReport(Id reportId) {

        HttpResponse response = execute(HttpMethod.GET, REPORTS_RESOURCE + reportId);

        return (MatrixReport) JSON.deserialize(response.getBody(), MatrixReport.class);
    }
}

The request produced is:

Method: GET
URL: https://x–x.cs83.my.salesforce.com/services/data/v44.0/analytics/reports/XXXX

But I am getting this error:

{"message":"Session expired or invalid","errorCode":"INVALID_SESSION_ID"}

I thought that since the recent release using URL.getOrgDomainUrl() meant to access the REST API meant I didn't need to authenticate.

Sandbox org is on Spring '19 Patch 19.4

Questions

  1. What am I doing wrong?
  2. How can I fix it?

NOTE: I fixed this using Named Credentials you can read more here

Best Answer

Based on the comments, it seems you are using a Guest User here to be able to get a Session Id and utilize that in your code using request.setHeader('Authorization', 'OAuth ' + UserInfo.getSessionID());

The error INVALID_SESSION_ID you are receiving is expected in that case. Refer to Guest user session ID returned NULL in UserInfo.getSessionId() knowledge article. It discusses exactly this scenario which you are facing now.

You will need to adjust the approach here as there's no workaround to get past this.