1

How to create or set a session in sales force.I am not using site.login for logging.I am manually checking username and password(Custom Field) and once checked.I have to create a session when navigating to another page

2

ONE OPTION -

First of all, create a Custom Label 'Login_Request' with value as-

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:partner.soap.sforce.com"><soapenv:Header><urn:organizationId>@@@@OrgId@@@@</urn:organizationId></soapenv:Header><soapenv:Body><urn:login><urn:username>@@@@Username@@@@</urn:username><urn:password>@@@@Password@@@@</urn:password></urn:login></soapenv:Body></soapenv:Envelope>

Next inside apex class Create the below method to login into system and get Session ID -

public string GetOrgAccessToken() {
        string sessionId;
        string orgId = **18DIGIT_ORG_ID**;
        string suborgId=orgId.substring(0,15);
        string orgbody=Label.Login_Request.replace('@@@@OrgId@@@@',suborgId);
        string userbody=orgbody.replace('@@@@Username@@@@',pHeader.**USERNAME**);
        string Pwdbody=userbody.replace('@@@@Password@@@@',pHeader.**PASSWORD**);
        string body = Pwdbody;
        HttpRequest req = new HttpRequest();
        req.setEndpoint('https://LOGIN_OR_TEST.salesforce.com/services/Soap/u/29.0');
        req.setMethod('POST');
        req.setHeader('Content-Type', 'text/xml;charset=UTF-8');
        req.setHeader('SOAPAction', '""');
        req.setTimeOut(30000);
        req.setBody(body);
        Http p = new Http();
        HttpResponse res = p.send(req);
        loginResponse = res.getbody();
        Xmlstreamreader reader = new Xmlstreamreader(res.getbody());
        while (reader.hasNext()) {
            if (reader.getEventType() == XmlTag.Characters) {
                if (string.valueof(reader.getText()).startswith(suborgId + '!')) {
                    sessionId = reader.getText();
                }
                if(string.valueof(reader.getText()).startswith('https://')){
                    getTicketsEndpoint = reader.getText();
                }
            }
            reader.next();
        }
        return sessionId;
    }

Pay special attention and replace the bold text. Important parameters are 18 Digit org ID, Username, Password, Endpoint. Ensure that endpoint base URL is login.salesforce.com for Production or DEV org and test.salesforce.com for Sandboxes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.