I am trying to make a web service call to insert a Account data from one salesforce org to another. I add username and password to the http header when making a callout however I get a http code error 401 saying unauthorized. How can I make a call to salesforce to insert a account record with basic http authentication?
Here is what I am trying to do:
Http http = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('https://mydomain-dev-ed.my.salesforce.com/services/data/v39.0/sobjects/Account/');
String username = 'theusername';
String password = 'thepasswork';
Blob headerValue = Blob.valueOf(username + ':' + password);
String authorizationHeader = 'BASIC ' +
EncodingUtil.base64Encode(headerValue);
req.setHeader('Authorization', authorizationHeader);
req.setMethod('POST');
req.setBody('{"Name" : "Express Logistics and Transport"}');
HttpResponse res = http.send(req);
system.debug('Res2******************' + res);
I do not want to use OAuth to autrhenticate. Is there anything wrong in the above code? What am I missing using the basic HTTP authentication mechanism?
Best Answer
Salesforce does not support the HTTP Basic Authentication mechanism. All valid API calls that require a session require a valid session ID. The two primary ways of obtaining this are by OAuth or by a SOAP login call. If you don't want to use OAuth, you can use SOAP to log in. All you need to do is export the Partner WSDL (Setup > Develop > API), take out all the parts you don't need, leaving just the login call and its input/output parameters, import this as a WSDL2Apex import, and you can call the login method directly in Apex without too much fuss.