WorkOS Docs Homepage
Pipes
API referenceDashboardSign In
Getting StartedOverviewOverviewConnection sharingConnection sharingMultiple connectionsMultiple connectionsSecuring authorizationsSecuring authorizationsCustom providersCustom providersOrganization-scoped providersOrganization-scoped providersAPI key providersAPI key providersRelayRelayProvidersProviders
API Reference
API Reference
Events
Events
Integrations
Integrations
Migrate to WorkOS
Migrate to WorkOS
SDKs
SDKs

Securing the authorization flow

How WorkOS protects Pipes OAuth authorizations, and how to bind an authorization to the user who started it.

On this page

  • Overview
  • The confirmation screen
  • Session binding
  • Register your return URL
  • Start the authorization
  • Finish the authorization
  • Errors and retries
  • Abandoned authorizations
  • Tie the verifier to the user who started the authorization

Overview

A Pipes authorization flow begins with a URL that takes the user to the provider’s OAuth consent screen. That URL is tailored to a specific user and, optionally, an organization, but whoever opens that URL and signs in at the provider decides which provider account gets connected. If the URL ends up with someone else, their provider account could be connected to the user who started the authorization.

This guide only applies if you start authorizations from your own UI with the API. The Pipes widget manages the handoff for you. If you’re building your own UI, Pipes offers two ways to protect the authorization:

  1. The confirmation screen shows whose account the provider account will be connected to before the user reaches the provider. This is the default.
  2. Session binding lets your server send a code_challenge and keep the matching code_verifier where only the user who started the authorization can reach it, such as their session. Pipes only saves the connected account when your server finishes the authorization with that verifier. This uses the same verifier-and-challenge pattern as PKCE. It’s stronger than the confirmation screen and replaces it, so your users see one less screen.

The confirmation screen

When enabled, Pipes shows a confirmation screen before sending the user to the provider. The screen says whose account the provider account is about to be connected to: the user’s email address, your project, and the organization for organization-owned providers. A user who was handed another user’s link can see the mismatch and cancel. If they cancel, the provider is never contacted. When the authorization included a return_to, Pipes redirects there with error=access_denied; otherwise, Pipes renders its own canceled page.

GitHub account connection confirmation in WorkOS Pipes

Session binding

Alternatively, you can send a code_challenge when you start the authorization, and Pipes holds the result instead of saving it when the user returns from the provider:

  1. Your server creates a random code_verifier, stores it where only the user starting the authorization can reach it, and sends a hash of it, the code_challenge, to the authorize endpoint.
  2. The user approves access at the provider. Pipes holds the result and sends the user to your return_to URL with a one-time connect_code.
  3. Your server sends the connect_code and the code_verifier to the finish endpoint, and Pipes saves the connected account.

The browser only ever sees the connect_code, and the code_verifier never leaves your server. Neither one is enough to finish the authorization alone. Unlike the confirmation screen, this protection doesn’t depend on the user noticing that an authorization URL belongs to someone else. Authorizations that send a code_challenge skip the confirmation screen: session binding replaces it, so opting in means one less screen for the user.

Register your return URL

Pipes only sends the connect_code to a return_to URL registered for an application in the same environment. In the Applications section of the Dashboard, open your application and go to the Redirects tab.

  • return_to must exactly match a registered redirect URI. A URI that only matches a wildcard entry is rejected.
  • Use HTTPS. HTTP is allowed only for loopback addresses such as localhost, which match on any port.
  • Don’t include a query string or fragment. Pipes adds connect_code and state as query parameters.

Start the authorization

The examples show two route handlers from a hypothetical Express app, not a complete application. They assume your sign-in and CSRF middleware already protect the start route and your server-side session contains userId. Use a secure, HTTP-only session cookie with SameSite=Lax, so the browser sends it when the user returns from the provider. These excerpts keep one pending authorization per session.

Generate a new verifier for each authorization: 32 random bytes, base64url encoded. Hash it with sha256 and base64url encode the result. Send that challenge with code_challenge_method: 'S256' and your registered return URL.

import crypto from 'node:crypto';
app.post('/integrations/:provider/authorize', async (req, res) => {
const codeVerifier = crypto.randomBytes(32).toString('base64url');
const codeChallenge = crypto
.createHash('sha256')
.update(codeVerifier)
.digest('base64url');
try {
const response = await fetch(
`https://api.workos.com/data-integrations/${encodeURIComponent(req.params.provider)}/authorize`,
{
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.WORKOS_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
user_id: req.session.userId,
return_to: 'https://example.com/integrations/callback',
code_challenge: codeChallenge,
code_challenge_method: 'S256',
}),
},
);
if (!response.ok) {
return res.status(502).send("Couldn't start the authorization.");
}
const authorization = await response.json();
// Don't redirect unless WorkOS confirms it will wait for your server.
if (
authorization.completion !== 'finish_required' ||
!authorization.state
) {
return res.status(502).send("Couldn't start the authorization.");
}
req.session.pendingAuthorization = {
state: authorization.state,
codeVerifier,
};
res.redirect(303, authorization.url);
} catch {
res.status(502).send("Couldn't start the authorization.");
}
});

Before redirecting, check that Pipes returned completion: 'finish_required' and a state value. Without that acknowledgment, Pipes could save the connected account at the provider callback without waiting for your server’s proof. Store the verifier and returned state before sending the user to the authorization URL. The examples use the user’s session; see Tie the verifier to the user who started the authorization for the alternative.

Finish the authorization

Pipes returns the user to your registered URL with a connect_code or an error. Before handling either result, compare the returned state with the state you stored for the pending authorization. If it’s missing or doesn’t match, leave the pending authorization alone: an unrelated request should not cancel an authorization in progress.

Once state matches, clear the pending authorization. If the user canceled or the provider refused access, redirect to your application’s error state. Otherwise, finish immediately with the stored verifier. Use an API key for the same environment that started the authorization.

app.get('/integrations/callback', async (req, res) => {
res.set({ 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer' });
const { connect_code: connectCode, error, state } = req.query;
const pending = req.session.pendingAuthorization;
// An unrelated request must not clear the authorization in progress.
if (!pending || typeof state !== 'string' || state !== pending.state) {
return res.redirect(303, '/integrations?authorization=failed');
}
delete req.session.pendingAuthorization;
if (typeof error === 'string') {
return res.redirect(303, '/integrations?authorization=denied');
}
if (typeof connectCode !== 'string') {
return res.redirect(303, '/integrations?authorization=failed');
}
try {
const response = await fetch(
'https://api.workos.com/data-integrations/finish',
{
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.WORKOS_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
connect_code: connectCode,
code_verifier: pending.codeVerifier,
state,
}),
},
);
if (!response.ok) {
return res.redirect(303, '/integrations?authorization=failed');
}
const { connected_account: connectedAccount } = await response.json();
res.redirect(
303,
`/integrations?connected=${encodeURIComponent(connectedAccount.id)}`,
);
} catch {
// Don't retry, even on a network error. Check for a connected account or start over.
res.redirect(303, '/integrations?authorization=failed');
}
});

For the callback route:

  • Read connect_code in the first route that receives it, then redirect to an application URL that doesn’t contain it, even after an API or network failure. Each extra redirect that carries the code leaves another copy in browser history and server logs.
  • Don’t pass connect_code through sign-in, for example in a next or return_to parameter on your login page. Sign-in systems store that URL and replay it after authentication, so the code is kept and sent a second time.
  • Use Cache-Control: no-store to prevent caching of the callback response.
  • Use Referrer-Policy: no-referrer to prevent the callback URL from being forwarded as a referrer.
  • Treat connect_code as sensitive information. Keep it out of application logs and analytics.

These precautions limit how many copies of the code exist. A leaked connect_code isn’t a vulnerability by itself: it works once, expires quickly, and is useless without the verifier.

Pipes holds the result for about 90 seconds after the user returns from the provider. After that, the connect_code stops working, nothing is saved, and the user has to start over. On success, POST /data-integrations/finish returns the connected account in the connected_account response field.

That window is easy to miss if your return route requires sign-in and the user isn’t signed in on that device, which is common when the authorization link arrived by text message or email. Where you can, have the user sign in before you send them to the provider, and handle an expired finish as a normal restart rather than an error.

Errors and retries

A held authorization finishes at most once. Treat every finish call as the only attempt:

  • An incorrect code_verifier uses up the connect_code. Calling finish again with the right verifier fails.
  • A connect_code that’s already been used, has expired, or belongs to another environment fails with invalid_connect_code.
  • Don’t retry a failed finish call, including after a network error. Check whether the user’s connected account exists, or start a new authorization.

Only act on a returned error when state matches the pending authorization you stored. If the error response has no matching state, the callback uses the generic failure path and leaves the pending authorization alone.

Code Endpoint Meaning
connect_finish_unavailable authorize Session-bound authorization isn’t available for your environment yet.
return_to_requires_exact_match authorize return_to only matches a wildcard redirect URI. Register the exact URL.
invalid_return_to authorize return_to is missing, doesn’t exactly match a registered redirect URI, isn’t HTTPS, or includes a query string or fragment.
invalid_connect_code finish The connect_code is unknown, expired, already used, or the verifier was wrong.

All of these return a 400 status.

Abandoned authorizations

If the user approves access at the provider but the authorization is never finished, no connected account is saved in Pipes. The provider may still list your app in the user’s connected apps until the user removes it there.

Tie the verifier to the user who started the authorization

Session binding only works if the code_verifier is available to the user who started the authorization and to no one else. There are two ways to do that.

Store it in the user’s session. The examples above do this. Another user’s browser that arrives at your return URL has a different session and no verifier to finish with, so there’s nothing more to check.

Store it on a server-side record and check the signed-in user. Use this when there’s no browser session at the start, such as when a background job or webhook handler starts the authorization and you send the user the link. Save the verifier on your own record of the authorization, along with the user_id you sent to the authorize endpoint. Require sign-in on your return route, look up the record by state, and call finish only if the signed-in user matches the stored user_id. Someone who opens a link meant for another user signs in as themselves, fails that check, and leaves the record untouched.

In this design, that check is the only protection, so make it hard to skip. Put it inside the function that returns the verifier instead of repeating it in each route. Keep a test that replays the attack: arrive with one user’s state while signed in as another, and confirm the request is refused and the record isn’t consumed.

Don’t look up the verifier by state alone. If a table keyed by state hands the verifier to whoever returns with a matching value, any browser can finish any authorization, and the binding protects nothing.

Custom providers Define your own provider in Pipes when the one you need isn't in the WorkOS catalog
Up next
© WorkOS, Inc.
FeaturesAuthKitSingle Sign-OnDirectory SyncAdmin PortalFine-Grained Authorization
DevelopersDocumentationChangelogAPI Status
ResourcesBlogPodcastPricingSecuritySupport
CompanyAboutCustomersCareersLegalPrivacy
© WorkOS, Inc.