function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

Basic HTTP Authentication for REST service


I have exposed a custom REST service through Apex code. I have given the following curl command to get the data from the API and it works fine if passed the session id in the header.

curl -H 'Authorization: Bearer 00D36000000wE02!ARAAQNag09f5_h7z8_ArS_JFo6f1o9Ag4C7y201UJDlyP66MSE1YrL7brsqS5CmCOO5' -H 'X-PrettyPrint:1'

But when I tried to use the Basic HTTP authentication it gives me below error. I have encoded the username and the password with base64

curl -H 'Authorization: Basic <username:password>'

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

What I'm doing wrong here. Do I need to make any change in the back end code as well?
could pls share your callout code.. 

This is one example that work fine

String username='UserName';
String pwd='Password';

HttpRequest request = new HttpRequest();
request.setHeader('Content-Type', 'text/xml;charset=UTF-8');
request.setHeader('SOAPAction', '""');
request.setBody('<Envelope xmlns=""><Header/><Body><login xmlns=""><username>' + userName+ '</username><password>' + pwd+ '</password></login></Body></Envelope>');
Dom.XmlNode resultElmt = (new Http()).send(request).getBodyDocument().getRootElement()
  .getChildElement('Body', '')
  .getChildElement('loginResponse', '')
  .getChildElement('result', '');
final String SERVER_URL = resultElmt.getChildElement('serverUrl', '') .getText().split('/services')[0];
final String SESSION_ID = resultElmt.getChildElement('sessionId', '') .getText();

final PageReference theUrl = new PageReference(SERVER_URL + 'services/data/v26.0/sobjects/');

request = new HttpRequest();
request.setHeader('Authorization', 'Bearer '+SESSION_ID);

String body = (new Http()).send(request).getBody();
system.debug('=body ======='+body );
JSONParser parser = JSON.createParser(body);


Here in this example you have used the session id. But in my code I'm trying to use HTTP basic authentication. 
So the client will be passing : Authorization: Basic <username:password>

Username:Password is encoded in Base64. Normally its working for other rest service. Not sure why its not working in Salesforce.
Admin Atile 1Admin Atile 1
It should be possible to expose rest api and basic authentication, especially considering webhook's cenarios.