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_IDandCLIENT_SECRET). - Target API: Identify the external API or service you wish to interact with, and understand their authentication requirements.
Step-by-Step Implementation
- Create an Apex class in Developer Console or VS Code.
- Define endpoint details and OAuth payload parameters.
- Construct an HTTP POST request and send the urlencoded payload.
- Parse the returned JSON to extract the
access_tokenstring.
Create a new Apex class that will handle the process of obtaining an access token from the Salesforce Developer Console or your preferred IDE.
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).USERNAMEandPASSWORD: Salesforce username and user password appended with your security token.
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;
}
}
}
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);).
- Grant Type: Resource Owner Password Credentials (
grant_type=password). - Request Method: HTTP POST with
application/x-www-form-urlencodedbody 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.