Skip to main content

How to Get a Salesforce Session ID: SOAP Login, OAuth 2.0 & Apex Methods

In plain words: A Salesforce Session ID (or OAuth access token) acts as a digital key that proves your identity to Salesforce. Once authenticated, external applications pass this token in the Authorization: Bearer <Session_ID> header to query database records, execute REST/SOAP APIs, or trigger automations without re-entering login credentials on every request.

Connecting third-party platforms, microservices, or custom scripts to Salesforce requires a valid authentication token. Whether you are building an integration using legacy SOAP web services or modern REST APIs, obtaining a session ID is the first step. Below is a breakdown of how to retrieve session IDs using SOAP login requests, native Apex methods, and modern OAuth 2.0 standards.

1. Understanding Session IDs & Auth Methods in Salesforce

Salesforce provides several ways to authenticate and retrieve session tokens depending on your architectural context:

  • SOAP Partner/Enterprise API Login: A classic XML-based web service request that authenticates username, password, and security token, returning a session ID and instance server URL.
  • Native Apex Session Retrieval: In Apex controllers or batch jobs, retrieving active user context without making outbound callouts via UserInfo.getSessionId() or PageReference tokens.
  • Modern OAuth 2.0 Token Flows: Connected App flows (such as JWT Bearer, Client Credentials, or Web Server flow) that return standard Bearer access tokens without exposing raw passwords.
360 Authentication Architecture Card:
  • SOAP Endpoints: https://login.salesforce.com/services/Soap/u/60.0 (Production) and https://test.salesforce.com/services/Soap/u/60.0 (Sandbox).
  • Required SOAP Headers: Content-Type: text/xml; charset=UTF-8 and SOAPAction: "".
  • In-Apex Retrieval: UserInfo.getSessionId() or Page.SessionIdPage.getContent().toString().
  • Modern Best Practice: OAuth 2.0 Client Credentials / JWT Flow with Salesforce Named Credentials.

2. Method 1: Obtaining Session ID via SOAP Login API

The SOAP Login API is a direct way for external applications and middleware to obtain a session ID using an HTTP POST request.

Step-by-Step Implementation: The SOAP Login Request
  1. Determine Environment Endpoint: Use login.salesforce.com for Production/Developer orgs and test.salesforce.com for Sandboxes.
  2. Configure Headers: Set Content-Type: text/xml; charset=UTF-8 and SOAPAction: "".
  3. Append Security Token to Password: If IP restrictions are not relaxed, concatenate your account password with your 24-character security token (e.g., MyPassword123ABCxyzSecurityToken).
<!-- SOAP Login Request Payload -->
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:partner.soap.sforce.com">
   <soapenv:Body>
      <urn:login>
         <urn:username>developer@mycompany.com</urn:username>
         <urn:password>Password123!YourSecurityTokenHere</urn:password>
      </urn:login>
   </soapenv:Body>
</soapenv:Envelope>

When Salesforce successfully validates the credentials, it returns a 200 OK XML response containing the <sessionId> and your assigned <serverUrl>:

<!-- SOAP Login Response (Extracting sessionId) -->
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns="urn:partner.soap.sforce.com">
   <soapenv:Body>
      <loginResponse>
         <result>
            <serverUrl>https://yourInstance.my.salesforce.com/services/Soap/u/60.0/00D...</serverUrl>
            <sessionId>00D5g00000KXYZ!AQEAQO1234567890abcdef...</sessionId>
            <userId>0055g00000AbCdEF</userId>
         </result>
      </loginResponse>
   </soapenv:Body>
</soapenv:Envelope>

3. Method 2: Retrieving Session ID Inside Apex Code

When writing server-side Apex that needs to make callouts back into Salesforce REST endpoints or external APIs, you can retrieve the session token directly in code:

public with sharing class SalesforceSessionService {

    // Retrieves the active user session ID
    public static String getActiveSessionId() {
        // Standard synchronous context retrieval
        String sessionId = UserInfo.getSessionId();
        
        // If running in asynchronous Apex (Queueable/Batch), UserInfo.getSessionId() may return null.
        // In such scenarios, use Named Credentials instead of raw session IDs.
        return sessionId;
    }

    // Example: Making a self-REST callout using the Session ID
    public static String queryViaRest(String soql) {
        HttpRequest req = new HttpRequest();
        req.setEndpoint(URL.getOrgDomainUrl().toExternalForm() + '/services/data/v60.0/query?q=' + EncodingUtil.urlEncode(soql, 'UTF-8'));
        req.setMethod('GET');
        req.setHeader('Authorization', 'Bearer ' + getActiveSessionId());
        req.setHeader('Accept', 'application/json');

        Http http = new Http();
        HttpResponse res = http.send(req);
        return res.getBody();
    }
}

4. Modern Alternative: OAuth 2.0 vs. SOAP Password Login

While SOAP login remains widely supported, modern enterprise architectures favor OAuth 2.0 flows through Connected Apps:

  • Client Credentials Flow: Server-to-server integration standard that authenticates via Client ID and Client Secret without needing dedicated user passwords.
  • JWT Bearer Token Flow: Uses public/private X.509 certificates to exchange a digitally signed token for a scoped access token without human login prompts.
  • Salesforce Named Credentials: Automatically authenticates, securely stores refresh tokens, and injects Authorization headers into Apex callouts with zero custom token-management code.

5. Common Traps & Security Best Practices

Security Trap: Hardcoding Passwords and Exposing Session IDs in Logs
Hardcoding user passwords, client secrets, or security tokens inside plaintext files or version control introduces severe compliance risks. Additionally, printing raw session IDs to System.debug() logs exposes temporary admin access to anyone with debug log viewing permissions.
Core Rule: Protect session tokens like passwords. For external integrations, prefer OAuth 2.0 Connected Apps or Salesforce Named Credentials over hardcoded SOAP username/password requests.
  • Handle Session Timeouts: Session IDs expire based on org session policies (e.g., 2 hours). External integrations must catch 401 Unauthorized responses and trigger a fresh login handshake.
  • Use My Domain URLs: Always direct API traffic to your organization's custom My Domain URL (https://company.my.salesforce.com) rather than generic instance URLs (e.g., na123.salesforce.com) to prevent routing failures during server maintenance.
  • Enforce Least Privilege: Ensure integration users have dedicated integration profiles/permission sets with only the minimum required CRUD permissions.

Summary

Obtaining a session ID is a fundamental building block for integrating external applications with Salesforce. Whether using the SOAP Login API, native Apex UserInfo.getSessionId(), or modern OAuth 2.0 Connected Apps, adhering to secure token handling and authentication best practices ensures robust, reliable, and compliant integrations across your enterprise ecosystem.