2

I am getting this HTTP error:

Status=Unauthorized, StatusCode=401

When I try and access the Tooling REST API from an Lightning component Apex controller being used inside Salesforce, running as System Administrator.

This is the HTTP GET Request Endpoint

https://x--x.my.salesforce.com/services/data/v44.0/tooling/query?q=Select+Id,ActiveVersion.VersionNumber,LatestVersion.VersionNumber,DeveloperName+From+FlowDefinition+ORDER+BY+DeveloperName

This is the method executing the request:

public static HttpResponse executeCallout(String method, String resourceName, String requestBody) {

    HttpRequest request = new HttpRequest();

    if (method == 'PATCH') {
        request.setMethod('POST');    
    } else {
        request.setMethod(method);    
    }

    request.setEndpoint(URL.getOrgDomainUrl().toExternalForm() + resourceName);

    request.setHeader('Authorization', 'Bearer '+ UserInfo.getSessionId());

    request.setHeader('Accept', 'application/json');
    request.setHeader('X-PrettyPrint', '1');
    request.setHeader('Content-Type', 'application/json');

    if (String.isNotBlank(requestBody)) {
        request.setBody(requestBody);
    }

    return new Http().send(request);
}

Where the method is equal to GET and requestBody is null and resourceName is equal to:

/services/data/v44.0/tooling/query?q=Select+Id,ActiveVersion.VersionNumber,LatestVersion.VersionNumber,DeveloperName+From+FlowDefinition+ORDER+BY+DeveloperName

I've checked the length of UserInfo.getSessionId() and it's returning a value of length 112

Questions

  1. What is causing the problem?
  2. How can I fix it?
Robs
  • 9,336
  • 20
  • 106
  • 215
  • 1
    @kurunve I don't believe it's a duplicate. That question is over 3 years old. Salesforce platform has moved on since then. And the related bug was fixed in Winter '18. – Robs May 01 '19 at 11:26
  • indeed you are correct, that was bad example, I have removed comments. It two words, I have recently tried to do same, and it seems that session from auraenabled method does not allow to make rest/metadata or tooling api calls, only lightning. I am unable to find a good proof why, but I went with of the workarounds. Some ideas about why those sessions are different can be found here -- https://salesforce.stackexchange.com/questions/55306/how-to-call-a-salesforce-rest-url-from-lightning-component. – kurunve May 01 '19 at 11:37
  • 2
    Session ID from lightning is not api enabled. You have to use named credentials – Pranay Jaiswal May 01 '19 at 11:45

0 Answers0