How to connect an external service with OAuth
This guide shows you how to connect one installation of your app to an account at a different service. It uses the authorization code flow of OAuth. A person clicks a button on the page of your app. The service opens in a new window, and the person gives access. Your server keeps the tokens of the service in labels of the installation.
@picked/app-kit does the OAuth steps that are the same for each service. Your app gives two
functions: authorize builds the authorization URL of the service, and complete exchanges
the code for tokens.
You need these items:
- An app with a server that uses
@picked/app-kit, and anapp-homepage. How to add a page to the dashboard shows the page. - An OAuth client at the service: a client ID and a client secret.
The examples use a service at crm.example.com. Use the addresses and the scopes that your
service gives.
1. Register the callback address
At the service, register this callback address for your OAuth client:
<APP_PUBLIC_URL>/oauth/callbackAPP_PUBLIC_URL is the origin of your app, for example https://crm-app.example.com.
readAppEnvironment returns it as publicUrl. Refer to
App environment variables for its value on each host.
The callback must have the same host as the page of your app. The new window starts on the origin of the page, and sets a cookie for that host only. The callback reads that cookie.
If you work on your computer, use one host name for the page and the callback. For example,
the dashboard shows the page from http://localhost:4103. Then the callback address is
http://localhost:4103/oauth/callback, not http://127.0.0.1:4103/oauth/callback. On an
http: address of localhost, 127.0.0.1 or [::1], the cookie has the name
picked-oauth-<port>. Two apps on different ports do not share it.
Keep the client ID and the client secret in the environment of your server. In this guide,
they are CRM_CLIENT_ID and CRM_CLIENT_SECRET. If each customer has an OAuth client of
their own, keep the client in labels of the installation in place of the environment. Refer
to How to store data for an installation.
2. Add a button that opens the authorization window
On the page, call authorizeInPopup from a click handler. Give it the session token from
keepConnected. To send a value to your server, such as a region that the person chose, give it
as params.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
</head>
<body>
<select id="region">
<option value="us">United States</option>
<option value="eu">Europe</option>
</select>
<button id="connect" type="button">Connect CRM</button>
<p id="status"></p>
<script type="module">
import { authorizeInPopup, autoResize, keepConnected } from '/app-kit/frame.js'
const connection = await keepConnected()
autoResize()
document.getElementById('connect').addEventListener('click', async () => {
const result = await authorizeInPopup({
sessionToken: connection.context().sessionToken,
params: { region: document.getElementById('region').value },
})
document.getElementById('status').textContent = result.message
})
</script>
</body>
</html>authorizeInPopup opens a new window at /oauth/start on the origin of the page. When that
window is ready, authorizeInPopup sends the session token and params to that window only.
The session token does not go in an address.
Do not put an await before authorizeInPopup in the handler. The browser can stop a new
window that does not come directly from a click.
With an expired session token, the result is Sign in again.
keepConnected gets a new session
token before the token expires. The handler reads connection.context() when the person
clicks. The handler then has a session token that is not expired, and it does not wait for
the token.
keepConnected() works only in the iframe of the dashboard, so the page must open in Picked.
Some services separate the new window from your page. The window then stays open and
shows the result. authorizeInPopup returns when the person comes back to your page.
Give
authorizeInPopup a connected function that reads the connection from your server. It
returns a message when the connection exists, or null. Then authorizeInPopup waits up to
30 seconds for the connection that the window saves. Read the connection from your server
again after authorizeInPopup returns, and show it. The results of authorizeInPopup are in
authorizeInPopup.
3. Return the authorization URL
On your server, call startAuthorization for /oauth/start. Give it an authorize function
that returns the authorization URL of the service. Put the value of state(connection) in its
state parameter.
import { OAUTH_START_PATH, finishAuthorization, startAuthorization } from '@picked/app-kit/oauth'
import type { OAuthCallback } from '@picked/app-kit/oauth'
import {
createAppHandler,
installationClientFor,
json,
page,
readAppEnvironment,
} from '@picked/app-kit/server'
import { frameScript, serve } from '@picked/app-kit/node'
const port = process.env.APP_PORT ?? '4103'
const { privateKey, pickedKeys, publicUrl, frameAncestors } = readAppEnvironment(process.env, port)
const clientId = process.env.CRM_CLIENT_ID ?? ''
const clientSecret = process.env.CRM_CLIENT_SECRET ?? ''
const redirectUri = `${publicUrl}/oauth/callback`
const hosts: Record<string, string> = { us: 'crm.example.com', eu: 'eu.crm.example.com' }
function start(request: Request): Promise<Response> {
return startAuthorization(request, {
privateKey,
pickedKeys,
async authorize({ params, state }) {
const region =
typeof params === 'object' && params !== null && 'region' in params ? params.region : 'us'
if (typeof region !== 'string' || !(region in hosts)) {
return json({ error: { message: 'Choose a region' } }, 422)
}
const url = new URL(`https://${hosts[region]}/oauth/authorize`)
url.searchParams.set('response_type', 'code')
url.searchParams.set('client_id', clientId)
url.searchParams.set('redirect_uri', redirectUri)
url.searchParams.set('scope', 'contacts.read contacts.write')
url.searchParams.set('state', await state(region))
return url.toString()
},
})
}startAuthorization verifies the session token before it calls authorize. authorize gets
the session, the session token, the params from the page, and the state function.
state(connection) returns a state that holds the installation, the session token and the
value of a cookie. connection is a value that you choose. Use it when your app connects to
more than one service, or to more than one region of one service. The callback reads it back.
To refuse, return a Response with the body { "error": { "message": "<text>" } }. The
page gets that text as the result, and the browser does not go to the service.
4. Handle the callback
The service sends the browser to /oauth/callback with code and state. Call
finishAuthorization for this path. Give it a complete function that exchanges the code
for tokens.
finishAuthorization calls complete only when the state is correct and the browser has the
cookie from step 3. Otherwise, the window shows
This connection link has expired or was opened in another browser; start again.
Keep the tokens in a secret label of the installation. To write the label, make an installation client with the session token from the state:
async function complete({ state, url }: OAuthCallback): Promise<{ ok: boolean; message: string }> {
const code = url.searchParams.get('code')
if (code === null) return { ok: false, message: url.searchParams.get('error') ?? 'No code' }
const response = await fetch(`https://${hosts[state.connection]}/oauth/token`, {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
code,
redirect_uri: redirectUri,
client_id: clientId,
client_secret: clientSecret,
}),
})
if (!response.ok) return { ok: false, message: `The CRM answered ${response.status}` }
const grant: unknown = await response.json()
const client = installationClientFor(state, { privateKey, sessionToken: state.sessionToken })
await client.labels.set([
{
namespace: 'crm',
key: 'connection',
type: 'json',
value: JSON.stringify({ region: state.connection, grant }),
secret: true,
},
])
return { ok: true, message: 'Connected to the CRM' }
}The window sends the ok and message that complete returns to your page, and then
closes. authorizeInPopup returns them.
The callback request does not come from Picked, and it has no Authorization header. The
session token in the state is the only way to get a token for the installation, and it
expires as step 2 shows. If your app has offlineAccess, the client can get a token without
it.
5. Route the requests
Send the two paths to the functions, in the fallback of createAppHandler. Send each
method of /oauth/start to start: the window loads GET /oauth/start, then sends
POST /oauth/start.
const handler = createAppHandler({
pickedKeys,
async fallback(request) {
const { pathname } = new URL(request.url)
if (pathname === '/') return page(homeHtml, { frameAncestors })
if (pathname === '/app-kit/frame.js') return frameScript()
if (pathname === OAUTH_START_PATH) return start(request)
if (pathname === '/oauth/callback')
return finishAuthorization(request, { privateKey, complete })
return json({ error: 'not_found' }, 404)
},
})
serve(handler, Number(port))homeHtml is the page from step 2. OAUTH_START_PATH is /oauth/start. authorizeInPopup
always opens this path.
6. Revoke the grant when a person removes the app
When a person removes the app from a project, Picked sends installation.deleted before it deletes the
labels. Add onUninstall to the options of createAppHandler from step 5. Read the secret
label, and revoke the grant at the service:
const handler = createAppHandler({
pickedKeys,
async onUninstall(event) {
const client = installationClientFor(event, { privateKey })
const stored = await client.labels.get('crm', 'connection')
if (stored === undefined) return
const { region, grant } = JSON.parse(stored.value)
await fetch(`https://${hosts[region]}/oauth/revoke`, {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ token: grant.refresh_token, client_id: clientId }),
})
},
async fallback(request) {
const { pathname } = new URL(request.url)
if (pathname === '/') return page(homeHtml, { frameAncestors })
if (pathname === '/app-kit/frame.js') return frameScript()
if (pathname === OAUTH_START_PATH) return start(request)
if (pathname === '/oauth/callback')
return finishAuthorization(request, { privateKey, complete })
return json({ error: 'not_found' }, 404)
},
})If your server answers installation.deleted with an error, or does not answer, Picked
still deletes the installation and its labels.
To let a person stop the connection and keep the app, add a route that does the same. Then
remove the label with client.labels.delete([{ namespace: 'crm', key: 'connection' }]).
7. Use the connection
In a tool call or an event, read the label with the installation client of the request. Then call the service with its access token:
const stored = await installationClientFor(call, { privateKey }).labels.get('crm', 'connection')
if (stored === undefined) throw new Error('Connect the CRM on the app page in this project first')When the access token of the service expires, get a new one with its refresh token. Then set the label again.
Related
@picked/app-kit—startAuthorization,finishAuthorization, the cookie and the state, andauthorizeInPopup.- About app authentication — why the state carries the session token, and why a cookie binds the flow to one browser.
- How to store data for an installation — secret labels.
- How to send leads to Zoho CRM — an app that keeps the OAuth client of each customer in labels of the installation.
