3

I am attempting to call the Salesforce REST API from a Lightning Component. As per their documentation I have set up a named credential using the following settings:

Label: Salesforce REST
Name: SFDC_REST
URL: https://na39.salesforce.com
Certificate: null
Identity Type: Named Principal
Authentication Protocol: Password Authentication
Username: <my_username>
Password: <my_password>
Generate Authorization Header: true
Allow Merge Fields in HTTP Header: false
Allow Merge Fields in HTTP Body: false

All callouts made using this named credential return a 401 response with INVALID_SESSION_ID. I have seen other posts about using a custom merge header for OAuth but I am attempting to use basic auth here. I don't think I can generate my own basic auth header because I can't base64 encode the username/password.

Any insight on why the named credential is failing to authenticate? It seems like this should just be point-and-click setup and that I should just be able to reference the named credential in my endpoint as callout:SFDC_REST/services....

  • Have you enabled API access for the user/profile? Setup/Manage Users/Profiles/<edit the appropriate profile>/Administrative Permissions/<check API enabled> – The Salesforce General Jul 26 '17 at 20:41
  • What capability / data from the REST API interests you? – Kevin Venkiteswaran Jul 27 '17 at 4:37
  • For example, using the describe objects API to set up a page layout – dsharrison Jul 27 '17 at 4:38
  • If you want to read layout metadata check out Lightning Data Service (developer.salesforce.com/docs/atlas.en-us.lightning.meta/…) and UI API (developer.salesforce.com/docs/atlas.en-us.uiapi.meta/uiapi/…). Support for metadata and layout metadata is on the roadmap for LDS. – Kevin Venkiteswaran Jul 27 '17 at 22:37
  • Can the UI API be hit with a Lightning Session Id? All the documentation I read seemed like I needed an API capable Session Id. I'll look at the data service again but it seemed like that was only for working it single records and did not have information like search layouts. – dsharrison Jul 28 '17 at 16:23
5

Salesforce doesn't support direct Password Authentication to use the REST API. Typically you would go through an OAuth flow to get a valid access token to then call the service. You could go down this path by creating a Connected App and Authorization Provider, but that seems like a lot of work to get something you already have in Apex.

Instead, in Apex you can just use the UserInfo.getSessionId() in place of the access token in the Authorization header.

I've put together the following anonymous Apex to show how little is required. You will also need to add the Remote Site setting for your URL.

String restApi = URL.getSalesforceBaseUrl().toExternalForm() + '/services/data/v40.0/sobjects/';  

HttpRequest httpRequest = new HttpRequest();
httpRequest.setMethod('GET');
httpRequest.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
httpRequest.setEndpoint(restApi);

try {  
         Http http = new Http();   
         HttpResponse httpResponse = http.send(httpRequest);  
         if (httpResponse.getStatusCode() == 200 ) {
             string response = JSON.serializePretty( JSON.deserializeUntyped(httpResponse.getBody()) );  
             System.debug('REST API Response : ' + response );
         } else {  
               System.debug('httpResponse: ' + httpResponse.getBody());
               throw new CalloutException(httpResponse.getBody());
         }   

} catch( System.Exception e) {
         System.debug(LoggingLevel.ERROR, 'ERROR: '+ e);
         throw e;
}
  • Thanks for the info, I am very familiar with accessing the REST API in the way you mentioned and am doing so today from Visualforce. However, Salesforce does not provide a session id that is valid for the Rest Api from Lightning (even in Apex). It need some layout information from the Rest Api and it seems crazy to have to make a connected app and auth flow for that, but this may be the only option I guess. – dsharrison Jul 26 '17 at 23:54
  • @dsharrison I found a fairly good guide for the connected app and auth provider in Salesforce to Salesforce integration using Named Credentials in 5 lines. There is a more hackish solution in Getting Session ID in Lightning – Daniel Ballinger Jul 27 '17 at 0:19
  • 1
    There is the implication in How do I Call the Salesforce API from a Lightning Component? that you can use the OAuthToken from the named credential to explicitly set the Authorization Bearer header. – Daniel Ballinger Jul 27 '17 at 0:22
  • Daniel, thanks for the detailed updates. I am looking to have the component needing API access in a managed package so I will need to investigate what these additional steps mean for installers. Ideally I am not adding a bunch of setup work for something that should really be invisible to them (leveraging layouts their admin has already defined), but even some setup would be better than having them define layouts again in field sets or something similar. – dsharrison Jul 28 '17 at 16:25

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.