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
dai tran 6dai tran 6 

How can get Session Id from apex class by username & password?

I want create a custom Login Page.
After login will go to a Force.com site.
This site using a PushTopic, so i must get Sesstion Id of User.
How can get Session Id from apex class by username & password?
dai tran 6dai tran 6
In link https://www.sundoginteractive.com/blog/session-id-using-login-partner-api,
I not see send username and password to can login.
DuckyDucky
I know it's late but it might be helpful for others who refer to this page to look for the solution.
You can follow this code:
    private static HttpResponse authenticateByUsernamePassword(String useName, String password) {
        String uri = Url.getOrgDomainUrl().toExternalForm() + '/services/Soap/u/44.0';
        String body =
            '<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/"><Header/><Body><login xmlns="urn:partner.soap.sforce.com"><username>' +
            useName +
            '</username><password>' +
            password +
            '</password></login></Body></Envelope>';
        Http h = new Http();
        HttpRequest hRqst = new HttpRequest();
        hRqst.setEndpoint(uri);
        hRqst.setMethod('POST');
        hRqst.setHeader('SOAPAction', 'VALUE');
        hRqst.setHeader('Accept', 'text/xml');
        hRqst.setHeader('Content-type', 'text/xml');
        hRqst.setHeader('charset', 'UTF-8');
        hRqst.setBody(body);
        return h.send(hRqst);
    }

    private static string getSessionId(string username, string password) {
        HttpResponse response = authenticateByUsernamePassword(username, password);
        if (response.getStatusCode() == 200) {
            Dom.XmlNode resultElmt = response.getBodyDocument()
                .getRootElement()
                .getChildElement('Body', 'http://schemas.xmlsoap.org/soap/envelope/')
                .getChildElement('loginResponse', 'urn:partner.soap.sforce.com')
                .getChildElement('result', 'urn:partner.soap.sforce.com');
            return resultElmt.getChildElement('sessionId', 'urn:partner.soap.sforce.com').getText();
        }
        return null;
    }

 
Rohit Goyal 49Rohit Goyal 49
Hello @Ducky,
I have tried to use this method but it's not working. I have got 'Internal Server Error -500'User-added image
Rohit Goyal 49Rohit Goyal 49
Thx @Ducky, issue fixed.
https://salesforce.stackexchange.com/questions/53969/salesforce-api-login-status-server-error-statuscode-500
1. Set Your Ip in trusted IP Range.GoTo-->Setup > Security Controls > Network Access: Trusted IP Ranges
2. Set Password+SecruityToken. GoTo --> Administration Setup > My Personal Information > Reset my Security Token