How to Get a Salesforce Access Token from LWC Using Client Credentials Flow
Step 1: Setting Up the Connected App
Create a Connected App:
- Navigate to Setup in Salesforce.
- In the Quick Find box, type "App Manager" and click on it.
- Click New Connected App.
- Fill in the required fields:
- Connected App Name: Your app’s name.
- API Name: Auto-generated.
- Contact Email: Your email.
- Check the Enable OAuth Settings box.
- Enable the Connected App for client credential flow using checkbox in connectedapp
Configure OAuth:
- Set the Callback URL to your LWC’s endpoint.
- Select the appropriate OAuth scopes (e.g.,
api
,refresh_token
). - Save your changes.
Note the Consumer Key and Secret: After saving, you’ll see the Consumer Key and Consumer Secret. Keep these handy for later.
Step 2: Building the LWC
1. Create a Lightning Web Component
Run the following command in your Salesforce DX project or Use any tool
sfdx force:lightning:component:create --type lwc --componentname TokenFetcher --outputdir force-app/main/default/lwc
2. Implement the Component
Open the tokenFetcher.js
file and implement the logic to fetch the access token:
javascript
import { LightningElement } from 'lwc';
import getAccessToken from '@salesforce/apex/TokenController.getAccessToken';
export default class TokenFetcher extends LightningElement {
accessToken;
handleGetToken() {
getAccessToken()
.then(result => {
this.accessToken = result;
console.log('Access Token: ', this.accessToken);
})
.catch(error => {
console.error('Error retrieving token: ', error);
});
}
}
3. Create an Apex Controller
Create a file named TokenController.cls
with the following implementation for the client credentials flow:
public with sharing class TokenController {
@AuraEnabled(cacheable=false)
public static String getAccessToken() {
String clientId = 'YOUR_CLIENT_ID'; // Replace with your Client ID
String clientSecret = 'YOUR_CLIENT_SECRET'; // Replace with your Client Secret
String tokenUrl = 'https://yourInstance.salesforce.com/services/oauth2/token';
HttpRequest req = new HttpRequest();
req.setEndpoint(tokenUrl);
req.setMethod('POST');
req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
String body = 'grant_type=client_credentials' +
'&client_id=' + EncodingUtil.urlEncode(clientId, 'UTF-8') +
'&client_secret=' + EncodingUtil.urlEncode(clientSecret, 'UTF-8');
req.setBody(body);
Http http = new Http();
HttpResponse res = http.send(req);
if (res.getStatusCode() == 200) {
// Parse the response
Map<String, Object> jsonResponse = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
return (String) jsonResponse.get('access_token');
} else {
throw new AuraHandledException('Error retrieving access token: ' + res.getBody());
}
}
}
Important Notes
- Security: Make sure to store your Client ID and Client Secret securely. Avoid hardcoding them in your Apex class for production use. Consider using Named Credentials or Custom Settings for sensitive information.
- Instance URL: Replace
yourInstance
with the correct Salesforce instance (e.g.,login
for production ortest
for sandbox).
Step 3: Testing the LWC
- Deploy your component to Salesforce.
- Add your LWC to a Lightning page.
- Click the button to retrieve the access token and check the console for the output.
Conclusion
In this updated blog, we demonstrated how to use the client credentials flow to obtain a Salesforce access token using a Lightning Web Component and Apex. This method allows server-to-server integration without user intervention, making it suitable for background processes and automated tasks.
Comments
Post a Comment