Hey there, fellow JavaScript aficionado! Ready to dive into the world of Salesforce integrations? Today, we're focusing on the crucial part of any integration: the auth flow. Let's get your users securely connected to Salesforce in no time!
Before we jump in, make sure you've got:
Got those? Great! Let's roll.
Salesforce offers two main OAuth flows:
For most user-facing integrations, we'll be using the Web Server Flow. It's more secure and gives you more control. Plus, it plays nicely with server-side apps.
First things first, we need to send our users to Salesforce to log in. Here's how:
const authUrl = `https://login.salesforce.com/services/oauth2/authorize? response_type=code& client_id=${YOUR_CLIENT_ID}& redirect_uri=${YOUR_REDIRECT_URI}`; // Redirect the user to authUrl
Once the user logs in, Salesforce will redirect them back to your app with an authorization code. Catch it like this:
app.get('/oauth/callback', (req, res) => { const { code, error } = req.query; if (error) { // Handle error return; } // Use the code to get tokens });
Now, let's trade that code for some juicy tokens:
const tokenResponse = await fetch('https://login.salesforce.com/services/oauth2/token', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ grant_type: 'authorization_code', code, client_id: YOUR_CLIENT_ID, client_secret: YOUR_CLIENT_SECRET, redirect_uri: YOUR_REDIRECT_URI }) }); const { access_token, refresh_token } = await tokenResponse.json();
Store these tokens securely. Your database, a secure cookie, wherever – just keep 'em safe!
Now you're ready to make authenticated requests to Salesforce:
const response = await fetch('https://your-instance.salesforce.com/services/data/v52.0/query?q=SELECT+Id+FROM+Account', { headers: { 'Authorization': `Bearer ${access_token}` } });
Access tokens expire. When they do, use your refresh token to get a new one:
const refreshResponse = await fetch('https://login.salesforce.com/services/oauth2/token', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ grant_type: 'refresh_token', refresh_token: YOUR_REFRESH_TOKEN, client_id: YOUR_CLIENT_ID, client_secret: YOUR_CLIENT_SECRET }) }); const { access_token: new_access_token } = await refreshResponse.json();
Don't forget these security best practices:
state
parameter to prevent CSRF attacksThings don't always go smoothly. Be prepared to handle:
Graceful error handling will keep your users happy and your integration robust.
Before you ship, make sure to:
And there you have it! You've just built a solid auth flow for your Salesforce integration. Remember, this is just the beginning. From here, you can start building out the rest of your integration, adding more features and functionality.
Keep exploring, keep building, and most importantly, keep having fun with it!
Check out these resources:
Now go forth and integrate! You've got this! 🚀