Back

How to build a public Salesforce integration: Building the Auth Flow

Jul 17, 20246 minute read

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!

Prerequisites

Before we jump in, make sure you've got:

  • A Salesforce Developer Account (if you don't have one, go grab it – it's free!)
  • A Connected App set up in your Salesforce org

Got those? Great! Let's roll.

OAuth 2.0 Flow: The Basics

Salesforce offers two main OAuth flows:

  1. Web Server Flow
  2. User-Agent Flow

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.

Building the Auth Flow

Step 1: Kick off the OAuth dance

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

Step 2: Handle the callback

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 });

Step 3: Exchange code for 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!

Step 4: Use the access token

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}` } });

Keeping it Fresh: The Refresh Token Flow

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();

Security First!

Don't forget these security best practices:

  • Implement PKCE (Proof Key for Code Exchange) for added security
  • Use a state parameter to prevent CSRF attacks
  • Always use HTTPS

Handling Errors Like a Pro

Things don't always go smoothly. Be prepared to handle:

  • Invalid tokens
  • Expired refresh tokens
  • Network errors

Graceful error handling will keep your users happy and your integration robust.

Test, Test, Test

Before you ship, make sure to:

  • Test the full auth flow manually
  • Implement automated tests for each step
  • Test error scenarios and edge cases

Wrapping Up

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!

Want to Learn More?

Check out these resources:

Now go forth and integrate! You've got this! 🚀