Authenticate using the SOAP login request
Login using the SOAP login request and from then on use the session token for making REST API requests.In this we need to pass Username and Password as credentials.Upon invocation, the API authenticates the credentials . It then returns the sessionId, the user ID associated with the logged-in username, and a URL that points to the Lightning Platform API to use in all subsequent API calls.If Salesforce returns a Login fault , try adding the security token at the end of the user’s password.
The limit is 3,600 calls to login() per user per hour. Exceeding this limit results in a “Login Rate Exceeded” error. After reaching the hourly limit, Salesforce blocks the user from logging in. Users can try to log in again an hour after the block occurred.
String username = 'rpatnaik@docmation.com';
String password = 'Docmation$30092';
String organisationId = '00D3OXXXXXX8X7x';
String loginXML = '';
loginXML+= '<?xml version="1.0" encoding="UTF-8"?>';
loginXML+= '<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="urn:partner.soap.sforce.com">';
loginXML+= '<SOAP-ENV:Header>';
loginXML+= '<ns1:LoginScopeHeader><ns1:organizationId>';
loginXML+= organisationId;
loginXML+= '</ns1:organizationId></ns1:LoginScopeHeader>';
loginXML+= '</SOAP-ENV:Header>';
loginXML+= '<SOAP-ENV:Body>';
loginXML+= '<ns1:login>';
loginXML+= '<ns1:username>'+username+'</ns1:username>';
loginXML+= '<ns1:password>'+password+'</ns1:password>';
loginXML+= '</ns1:login>';
loginXML+= '</SOAP-ENV:Body>';
loginXML+= '</SOAP-ENV:Envelope>';
request.setEndpoint(config.Community_Base_URL__c+'/services/Soap/u/50.0');
request.setMethod('POST');
request.setHeader('SOAPAction', 'login');
request.setHeader('Accept','text/xml');
request.setHeader('Content-Type', 'text/xml;charset=UTF-8');
request.setBody(loginXML);
try{
if(!Test.isRunningTest()){
HttpResponse response = new Http().send(request);
sessionId = response.getStatusCode() == 200 ? getValueFromXMLString(response.getBody(), 'sessionId') : null;
}
else{
sessionId = '';
}
}catch(Exception e){
}
}
System.debug( 'sessionId---'+sessionId);
return sessionId;
}
public static string getValueFromXMLString(string xmlString, string keyField){
String xmlKeyValue = '';
if(xmlString.contains('<' + keyField + '>')){
try{
xmlKeyValue = xmlString.substring(xmlString.indexOf('<' + keyField + '>')+keyField.length() + 2, xmlString.indexOf('</' + keyField + '>'));
}catch (exception e){
}
}
return xmlKeyValue;
Comments
Post a Comment