Lightning: Getting a 401 when calling @AuraEnabled Apex method to do a REST call

The Session Id for Lightning is specifically restricted from most API calls. This means that you need to use a Named Credential to enable access to the APIs. This is outlined in the documentation.

By security policy, sessions created by Lightning components aren’t enabled for API access. This prevents even your Apex code from making API calls to Salesforce. Using a named credential for specific API calls allows you to carefully and selectively bypass this security restriction.

The restrictions on API-enabled sessions aren’t accidental. Carefully review any code that uses a named credential to ensure you’re not creating a vulnerability.

So, you need to create a Named Credential back to the Salesforce API, then use that Named Credential instead of using UserInfo.getSessionId().


Follow up:

Using Named Credentials is fine - but it won't work in all cases. For instance - if I was to use Chatter, the identity used is the Named Credential authorized. This won't work.

Using a VF Page however, uses the current user's session. This seems to be what I need.

FOLLOW UP: 1-9-2019

I ran into this article which described exactly what I needed back then. It is a really good write up with great explanations, history and a references:

https://douglascayers.com/2018/09/10/calling-rest-api-from-lightning-components-without-named-credentials/

Kudos DOUGLAS C. AYERS