top of page
Blog Page(1902x420).jpg

Keep your business ahead with

Insights That Drive Innovation

How to Get Access Token in Salesforce Apex: A Step-by-Step Guide

If you’re building integrations with Salesforce, knowing how to get an access token is critical. This blog will walk you through the process of obtaining a Salesforce API token using Apex, so your app can communicate securely with Salesforce’s REST API.


We will also explore related concepts like the Salesforce security token, consumer key and secret, and explain why these credentials matter when accessing your Salesforce Developer Edition or production org.


What is an Access Token in Salesforce?


An access token is an authentication token issued by Salesforce after successful OAuth authentication. Your application includes this token in API requests to prove its identity.

Unlike the Salesforce security token (used alongside your password for login from untrusted networks), the access token is short-lived and specific to API sessions.


Prerequisites: What You Need


Before you can get an access token using Apex, make sure you have:


Salesforce Developer Edition account – free and perfect for testing.Connected App created in Salesforce.Consumer Key and Consumer Secret – credentials generated when you create the Connected App.The token endpoint URL (Salesforce token URL):


bash

CopyEdit



For Sandbox, use:

bash

CopyEdit



How to Create a Connected App & Find Consumer Key


  1. Go to Setup → type App Manager in Quick Find

  2. Click New Connected App

  3. Enter the basic information

  4. Enable OAuth Settings, set the callback URL (for backend flows, this could be anything valid).

  5. Add OAuth Scopes (e.g., Full Access, Perform requests on your behalf)

  6. Save

  7. Copy the Consumer Key and Consumer Secret – you will need these in your Apex code


How to Get Salesforce Access Token in Apex

To get the access token, make an HTTP POST request to the token URL with the required parameters:


  • grant_type=password

  • client_id (consumer key)

  • client_secret (consumer secret)

  • username (Salesforce username)

  • password (password + security token)


Note: If your Salesforce user is set up with two-factor authentication or IP restrictions, add your Salesforce security token to the end of your password.


Apex Example: Get Access Token

apex

CopyEdit



public class SalesforceAuthService {
    public class AuthResponse {
        public String access_token;
        public String instance_url;
        public String token_type;
        public String issued_at;
        public String signature;
    }

    public static String getAccessToken() {
        String consumerKey = 'YOUR_CONSUMER_KEY';
        String consumerSecret = 'YOUR_CONSUMER_SECRET';
        String username = 'YOUR_SALESFORCE_USERNAME';
        String password = 'YOUR_PASSWORD' + 'YOUR_SECURITY_TOKEN';

        String tokenUrl = 'https://login.salesforce.com/services/oauth2/token';

        HttpRequest req = new HttpRequest();
        req.setEndpoint(tokenUrl);
        req.setMethod('POST');
        req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
        req.setBody(
            'grant_type=password' +
            '&client_id=' + EncodingUtil.urlEncode(consumerKey, 'UTF-8') +
            '&client_secret=' + EncodingUtil.urlEncode(consumerSecret, 'UTF-8') +
            '&username=' + EncodingUtil.urlEncode(username, 'UTF-8') +
            '&password=' + EncodingUtil.urlEncode(password, 'UTF-8')
        );

        Http http = new Http();
        HTTPResponse res = http.send(req);

        if (res.getStatusCode() == 200) {
            AuthResponse authResponse = (AuthResponse) JSON.deserialize(res.getBody(), AuthResponse.class);
            System.debug('Access Token: ' + authResponse.access_token);
            return authResponse.access_token;
        } else {
            System.debug('Failed: ' + res.getBody());
            return null;
        }
    }
}

Replace placeholders (YOUR_CONSUMER_KEY, etc.) with actual values from your Salesforce org.


Using the Token

Once you have the token, include it as a Bearer token in your HTTP request headers:

apex

CopyEdit


req.setHeader('Authorization', 'Bearer ' + accessToken);

This authenticates your API call to Salesforce.


Where to Find Salesforce Security Token


If you’re wondering how to get the security token in Salesforce:


  • Log in to Salesforce → Click your avatar → Settings → Reset My Security Token

  • You’ll get the new security token via email.


What Are Consumer Key and Secret?


The Consumer Key identifies your app; the Consumer Secret proves ownership. Together, they authenticate your app to Salesforce’s OAuth service.


Conclusion


By following these steps, you can easily get an access token in Salesforce Apex, allowing secure integration with Salesforce APIs.


Whether you’re working in a Salesforce Developer Edition account, sandbox, or production, understanding the roles of the Salesforce access token, consumer key, consumer secret, and security token is essential for building secure, robust apps.


Need Help with Salesforce Integrations or API Setups?


At Cloud Science Labs, we simplify complex Salesforce development. We assist with token-based authentication, custom integrations, secure API connections, and more. If you are stuck or need expert guidance, our certified team is just an email away.Email us at digital@cloudsciencelabs.com and let us solve it together. 

 
 
 

Comments


bottom of page