Skip to main content

Using Apex Code to Obtain an Access Token

๐Ÿ’ฌ In plain words: An access token acts as a temporary digital key. Once an application logs in and proves its identity, it gets a short-lived token to safely access protected data without sending sensitive passwords over the network with every single request.

In today's interconnected digital landscape, securing data and ensuring authorized access to various resources is of utmost importance. Access tokens play a pivotal role in this process, serving as a secure and efficient way to authenticate and authorize users or applications. In this blog post, we'll explore how to leverage Apex code within the Salesforce ecosystem to obtain an access token for interacting with external APIs or services.

Understanding Access Tokens

Access tokens are credentials that are used to gain access to protected resources. They are typically short-lived and are granted after a successful authentication process. Once obtained, these tokens are sent with each subsequent API request to ensure that the request is coming from an authenticated and authorized source.

Prerequisites

Before diving into the code, make sure you have the following prerequisites in place:

  • Salesforce Developer Account: You'll need a Salesforce developer account to create and test Apex code.
  • Connected App: Create a connected app in your Salesforce org to establish the integration and obtain the necessary credentials (CLIENT_ID and CLIENT_SECRET).
  • Target API: Identify the external API or service you wish to interact with, and understand their authentication requirements.

Step-by-Step Implementation

๐ŸŽฌ Step-by-Step Implementation Process
  1. Create an Apex class in Developer Console or VS Code.
  2. Define endpoint details and OAuth payload parameters.
  3. Construct an HTTP POST request and send the urlencoded payload.
  4. Parse the returned JSON to extract the access_token string.
1. Create Apex Class

Create a new Apex class that will handle the process of obtaining an access token from the Salesforce Developer Console or your preferred IDE.

2. Define Constants & Parameters

You need to configure key values required for the Password Grant flow:

  • CLIENT_ID: Obtained when you create a connected app.
  • CLIENT_SECRET: Obtained from the connected app details.
  • TOKEN_ENDPOINT: The URL where you exchange credentials for a token (e.g., https://login.salesforce.com/services/oauth2/token).
  • USERNAME and PASSWORD: Salesforce username and user password appended with your security token.
3. Apex Provider Implementation
public class AccessTokenProvider {
    private static final String CLIENT_ID = 'your_client_id';
    private static final String CLIENT_SECRET = 'your_client_secret';
    private static final String TOKEN_ENDPOINT = 'https://login.salesforce.com/services/oauth2/token';
    private static final String USERNAME = 'your_username';
    private static final String PASSWORD = 'your_password_with_security_token';

    public static String getAccessToken() {
        HttpRequest request = new HttpRequest();
        request.setEndpoint(TOKEN_ENDPOINT);
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/x-www-form-urlencoded');
        
        String payload = 'grant_type=password' +
                         '&client_id=' + EncodingUtil.urlEncode(CLIENT_ID, 'UTF-8') +
                         '&client_secret=' + EncodingUtil.urlEncode(CLIENT_SECRET, 'UTF-8') +
                         '&username=' + EncodingUtil.urlEncode(USERNAME, 'UTF-8') +
                         '&password=' + EncodingUtil.urlEncode(PASSWORD, 'UTF-8');
                         
        request.setBody(payload);

        Http http = new Http();
        HttpResponse response = http.send(request);

        if (response.getStatusCode() == 200) {
            Map<String, Object> jsonResponse = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
            return (String) jsonResponse.get('access_token');
        } else {
            System.debug('Error Requesting Token: ' + response.getStatusCode() + ' - ' + response.getBody());
            return null;
        }
    }
}
4. Execution & Usage

Call the AccessTokenProvider.getAccessToken() method from your integration service to retrieve the bearer token and attach it to subsequent REST callout headers (request.setHeader('Authorization', 'Bearer ' + accessToken);).

⚠ SECURITY TRAP: Hardcoding sensitive credentials like Client Secret and User Passwords in Apex source code is strongly discouraged. Storing sensitive credentials in plain text creates major security vulnerabilities across sandboxes and source control repositories.
๐Ÿง  Key Takeaway: Use Named Credentials or Custom Metadata Types to manage API credentials securely. For enterprise integrations, prefer the OAuth 2.0 JWT Bearer Token Flow to avoid handling passwords entirely.
๐Ÿงญ 360 Card — Access Token Authentication Summary
  • Grant Type: Resource Owner Password Credentials (grant_type=password).
  • Request Method: HTTP POST with application/x-www-form-urlencoded body payload.
  • Gain: Programmatically fetches authorization tokens dynamically inside Apex for automated callouts.
  • Limits: Hardcoded passwords should strictly be limited to temporary dev testing or sandbox environments.

Security Considerations

Always follow platform security best practices to protect sensitive credential data across your org. Prefer using native declarative security tooling like Named Credentials or External Credentials whenever possible.

Conclusion

Access tokens are essential components of modern authentication and authorization systems. By implementing the steps outlined above, you can programmatically obtain access tokens in Apex to establish secure communication with external APIs. Always follow platform security best practices to protect sensitive credential data across your org.