OAuth 2.0 is a widely used authentication protocol that provides secure access to resources on behalf of a user or an application. In this blog post, we will walk through the process of obtaining a refresh token and then using it to acquire an access token in Salesforce using Apex code.
Step 1: Configure Connected App in Salesforce
- Log in to your Salesforce account.
- Go to Setup and search for "App Manager".
- Click on "New Connected App" and fill in the required details.
- Connected App Name: RefreshTokenApp
- API Name: RefreshTokenApp
- Enable OAuth Settings
- Callback URL: https://localhost
- Selected OAuth Scopes: Full access (refresh_token, offline_access)
Step 2: Obtain Refresh Token
public class RefreshTokenExample {
public static String refreshTokenFlow() {
String refreshToken = 'YOUR_REFRESH_TOKEN'; // Replace with your actual refresh token
HttpRequest req = new HttpRequest();
req.setEndpoint('https://login.salesforce.com/services/oauth2/token');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
String clientId = 'YOUR_CLIENT_ID'; // Replace with your actual client ID
String clientSecret = 'YOUR_CLIENT_SECRET'; // Replace with your actual client secret
String requestBody = 'grant_type=refresh_token&client_id=' + clientId + '&client_secret=' + clientSecret + '&refresh_token=' + refreshToken;
req.setBody(requestBody);
Http http = new Http();
HttpResponse res = http.send(req);
return res.getBody();
}
}
Step 3: Obtain Access Token Using Refresh Token
public class AccessTokenExample {
public static String getAccessToken() {
String refreshTokenResponse = RefreshTokenExample.refreshTokenFlow();
Map<String, Object> responseMap = (Map<String, Object>) JSON.deserializeUntyped(refreshTokenResponse);
String accessToken = (String) responseMap.get('access_token');
return accessToken;
}
}
Step 4: Test the Code and Output
public class MainTestClass {
public static void main(String[] args) {
String accessToken = AccessTokenExample.getAccessToken();
System.debug('Access Token: ' + accessToken);
}
}
Expected Output:
Upon executing the MainTestClass, you should see the access token printed in the Debug Logs.
DEBUG|Access Token: YOUR_ACCESS_TOKEN
Congratulations! You've successfully obtained an access token using a refresh token in Salesforce using Apex code. This token can now be used to make authorized API requests on behalf of the user or application.
Remember to replace placeholders like YOUR_REFRESH_TOKEN, YOUR_CLIENT_ID, and YOUR_CLIENT_SECRET with your actual values.
This blog post covered the process of obtaining a refresh token and using it to acquire an access token using Apex code in Salesforce. This authentication mechanism is crucial for building secure and seamless integrations with Salesforce APIs.