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.


Sample Code -

            HTTPRequest request = new HTTPRequest();
            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;
    }

Response - 

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns="urn:tooling.soap.sforce.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
    <loginResponse>
        <result>
            <metadataServerUrl>https://docmation.my.salesforce.com/services/Soap/m/41.0/00D8E00x009MIn</metadataServerUrl>
            <passwordExpired>false</passwordExpired>
            <sandbox>true</sandbox>
            <serverUrl>https://docmation.my.salesforce.com/services/Soap/T/41.0/00D8E0000009MIn</serverUrl>
            <sessionId>00D8xx0009MIn!AQUAQAKlWxxuowH_1DK7ic52WzqCrxgyDRaPsrr9L8JgGRpv7l5oBmVFJGSs2tsKuxWAPum7vT2IlM7AuGt7vf.qG.3M8R_</sessionId>
            <userId>0058E0000xxWmT4QAK</userId>
            <userInfo>
                <accessibilityMode>false</accessibilityMode>
                <chatterExternal>false</chatterExternal>
                <currencySymbol>£</currencySymbol>
                <orgAttachmentFileSizeLimit>5242880</orgAttachmentFileSizeLimit>
                <orgDefaultCurrencyIsoCode>GBP</orgDefaultCurrencyIsoCode>
                <orgDefaultCurrencyLocale>en_GB</orgDefaultCurrencyLocale>
                <orgDisallowHtmlAttachments>false</orgDisallowHtmlAttachments>
                <orgHasPersonAccounts>true</orgHasPersonAccounts>
                <organizationId>00D8x00009MInUAM</organizationId>
                <organizationMultiCurrency>false</organizationMultiCurrency>
                <organizationName>Docmation</organizationName>
                <profileId>00e580000xydBAAQ</profileId>
                <roleId>00E8E0000xbcdhUAA</roleId>
                <sessionSecondsValid>28800</sessionSecondsValid>
                <userDefaultCurrencyIsoCode xsi:nil="true"/>
                <userEmail>rpatnaik@docmation.com</userEmail>
                <userFullName>Raja Patnaik</userFullName>
                <userId>0058E000xWmT4QAK</userId>
                <userLanguage>en_US</userLanguage>
                <userLocale>en_GB</userLocale>
                <userName>rpatnaik@docmation.com</userName>
                <userTimeZone>Europe/London</userTimeZone>
                <userType>PowerPartner</userType>
                <userUiSkin>Theme3</userUiSkin>
            </userInfo>
        </result>
    </loginResponse>
</soapenv:Body>

But there is risk of encountering an error “LOGIN_RATE_EXCEEDED“

Comments

Popular posts from this blog

Introduction to Salesforce Agent Script: Build Predictable AI Agents

Anti-Patterns in Salesforce Agentforce: What to Avoid When Building AI Agents

MCP vs. Traditional APIs: Choosing the Right Integration Approach