Skip to content
Swingback, home

Add the widget

Apps without a server

The secret that signs identity tokens must stay off your users' devices. If your app has no backend, the widget can accept your auth provider's own tokens, or a small serverless function can hold the secret and sign.

Sign in with your auth provider#

If your users sign in with Firebase, Supabase, Clerk, Auth0 or another OpenID Connect provider, select it under Settings → Sign-in, in Your auth provider, enter what it needs, and click Save. The widget then accepts the token your provider already gave your app, as it is. There is no function to deploy and no secret to keep. What each provider needs:

  • Firebase: enter the Project id. Your app passes its ID token, from user.getIdToken().
  • Supabase: enter the Project URL, such as https://xyzcompany.supabase.co. Your app passes the session's access token.
  • Clerk: enter the Frontend API URL, your tokens' issuer. Your app passes the session token, from getToken().
  • Auth0: enter the Domain, and your application's client id or your API's identifier as the Audience. Your app passes an ID token, or an access token for your API.
  • Other (OpenID Connect): enter the Issuer, and your application's client id as the Audience. Your app passes an ID token for your application.

Swingback checks each token's signature with your provider's public keys, and signs in the user that its subject (sub) names. It keeps their name and picture, and their email only where the token says your provider verified it (email_verified). Supabase's tokens never say this, so Swingback keeps no email from them. A token that lives longer than a day is refused. Traits and companies need a token you sign: use a function for those.

In your app, the SDK's token function returns the token, or null when nobody is signed in. With Firebase:

JavaScript
import { getAuth } from "firebase/auth";
import { createSwingback } from "@swingback/js";

createSwingback({
  portal: "https://acme.w.swingback.dev",
  // Nobody signed in: no token, and people read, or write as guests.
  token: async () => (await getAuth().currentUser?.getIdToken()) ?? null,
});

With Supabase, the token is the session's:

JavaScript
token: async () => {
  const { data } = await supabase.auth.getSession();
  return data.session?.access_token ?? null;
},
  • Supabase projects must sign with JWT signing keys. A project still on its legacy JWT secret has no public key to read, so Swingback refuses to save it. Supabase's guide explains how to move to signing keys.
  • Clerk's session token names the user by their id alone. To show names, add "name":"{{user.full_name}}" to it in Clerk's dashboard, under Sessions → Customize session token.

Check a token, on the same page, checks your provider's tokens too: paste one to see who it signs in.

Your provider's keys#

Swingback keeps your provider's public keys for as long as the provider's cache headers allow, between 5 minutes and 24 hours (1 hour when the provider sets none). A token signed with a key it doesn't know yet makes it read the keys again, at most once a minute. If your provider can't be reached when Swingback reads its keys again, the keys it already has keep working.

Anonymous users#

If your app lets people in before they create an account, with Firebase's or Supabase's signInAnonymously, pass their tokens too. Where your portal allows guests, an anonymous user signs in as one: they vote, pass the security check before each post and comment, and their posts wait for approval as guests' posts do. Swingback keeps no email for them, and recognizes them again by the id your provider gave them.

When they create an account by linking it to the anonymous one (Firebase's linkWithCredential, Supabase's updateUser or linkIdentity), your provider keeps their id. Their next token signs them in as your customer, with everything they wrote as a guest. If they sign in to an account they already had instead, what they wrote as a guest goes to that account, as it does when a browser's guest signs in.

Where your portal doesn't allow guests, an anonymous user's token signs nobody in. Anyone can create anonymous users, the same way anyone can write as a guest, so Swingback accepts at most 30 new ones an hour from one address, and 2,000 an hour per workspace, in addition to your provider's own limits.

Sign tokens in a function#

A function you deploy holds the identity secret and signs your own tokens, with traits and companies if you want them:

  1. Your app calls the function with the session your authentication service already gave it.
  2. The function checks that session with the service, then signs a token for that user with your identity secret.
  3. The SDK hands the token to the widget, which signs your user in.
The function stands in for your server: it checks who is signed in, then signs.

You need the three values from Create an identity secret: the identity secret, si_…, which goes in the function's secrets, and the ids of the secret and of your workspace, idsec_… and ws_….

The signer#

The functions below share this file. It signs with Web Crypto, so it runs unchanged in Firebase's and Supabase's functions, Cloudflare Workers, and Node.js 20 or later:

JavaScript
// identity-token.js: signs with Web Crypto. Firebase, Supabase, Workers, Node.js 20+.
const encoder = new TextEncoder();

function base64url(bytes) {
  return btoa(String.fromCharCode(...bytes))
    .replaceAll("+", "-")
    .replaceAll("/", "_")
    .replace(/=+$/, "");
}

const encode = (object) => base64url(encoder.encode(JSON.stringify(object)));

export async function identityToken(user, { secret, secretId, workspaceId }) {
  const now = Math.floor(Date.now() / 1000);
  const header = encode({ alg: "HS256", typ: "JWT", kid: secretId });
  const claims = encode({
    iss: workspaceId,
    aud: "swingback",
    sub: String(user.id),
    iat: now,
    exp: now + 10 * 60, // 10 minutes: at most an hour
    email: user.email, // left out when undefined
    name: user.name,
  });
  const hmac = { name: "HMAC", hash: "SHA-256" };
  const raw = encoder.encode(secret);
  const key = await crypto.subtle.importKey("raw", raw, hmac, false, ["sign"]);
  const data = encoder.encode(`${header}.${claims}`);
  const signature = await crypto.subtle.sign("HMAC", key, data);
  return `${header}.${claims}.${base64url(new Uint8Array(signature))}`;
}

It signs who the user is. To send traits and companies too, add them to the claims, as The token describes.

Firebase#

Use a callable function: Firebase checks the caller's session before it runs, and your app calls it with Firebase's SDK. Put the signer next to it, with "type": "module" in the functions' package.json:

functions/index.js
import { HttpsError, onCall } from "firebase-functions/https";
import { defineSecret, defineString } from "firebase-functions/params";

import { identityToken } from "./identity-token.js";

// si_…, in Cloud Secret Manager
const secret = defineSecret("SWINGBACK_IDENTITY_SECRET");
const secretId = defineString("SWINGBACK_IDENTITY_SECRET_ID"); // idsec_…
const workspaceId = defineString("SWINGBACK_WORKSPACE_ID"); // ws_…

export const feedbackToken = onCall({ secrets: [secret] }, async (request) => {
  if (!request.auth) throw new HttpsError("unauthenticated", "Sign in first.");
  const { uid, token } = request.auth; // checked by Firebase
  // Anonymous users post as guests, until they link an account.
  const firebase = token.firebase ?? {};
  const linked = Object.keys(firebase.identities ?? {}).length > 0;
  if (firebase.sign_in_provider === "anonymous" && !linked) return { token: null };
  const user = {
    id: uid,
    // Verified addresses only: Swingback links an email to the customer who has it.
    email: token.email_verified ? token.email : undefined,
    name: token.name,
  };
  const keys = {
    secret: secret.value(),
    secretId: secretId.value(),
    workspaceId: workspaceId.value(),
  };
  return { token: await identityToken(user, keys) };
});

Store the secret with firebase functions:secrets:set SWINGBACK_IDENTITY_SECRET, put the two ids in functions/.env, and deploy. In your app, the SDK's token function calls it:

JavaScript
import { getAuth } from "firebase/auth";
import { getFunctions, httpsCallable } from "firebase/functions";
import { createSwingback } from "@swingback/js";

const feedbackToken = httpsCallable(getFunctions(), "feedbackToken");

createSwingback({
  portal: "https://acme.w.swingback.dev",
  // Nobody signed in: no token, and people read or post as guests.
  token: async () => {
    if (!getAuth().currentUser) return null;
    const { data } = await feedbackToken();
    return data.token;
  },
});

An iOS, Android or React Native app calls the same function with Firebase's SDK for its platform, from the SDK's token function: iOS, Android, React Native.

Supabase#

Use an Edge Function: withSupabase checks the caller's session and handles the browser's preflight requests. Put the signer in supabase/functions/_shared/:

supabase/functions/feedback-token/index.ts
import { withSupabase } from "npm:@supabase/server@1";

import { identityToken } from "../_shared/identity-token.js";

export default {
  fetch: withSupabase({ auth: "user" }, async (_req, ctx) => {
    // Anonymous users post as guests.
    if (ctx.jwtClaims?.is_anonymous) return Response.json({ token: null });
    const admin = ctx.supabaseAdmin.auth.admin;
    const { data, error } = await admin.getUserById(ctx.userClaims.id);
    if (error) throw error;
    const user = {
      id: data.user.id,
      // Confirmed addresses only: Swingback links an email to its customer.
      email: data.user.email_confirmed_at ? data.user.email : undefined,
      name: data.user.user_metadata?.full_name,
    };
    const token = await identityToken(user, {
      secret: Deno.env.get("SWINGBACK_IDENTITY_SECRET")!,
      secretId: Deno.env.get("SWINGBACK_IDENTITY_SECRET_ID")!,
      workspaceId: Deno.env.get("SWINGBACK_WORKSPACE_ID")!,
    });
    return Response.json({ token }, { headers: { "Cache-Control": "no-store" } });
  }),
};

Store the three values with supabase secrets set, and deploy. In your app:

JavaScript
import { createSwingback } from "@swingback/js";

import { supabase } from "./supabase"; // your createClient(…)

createSwingback({
  portal: "https://acme.w.swingback.dev",
  token: async () => {
    const { data: auth } = await supabase.auth.getSession();
    if (!auth.session) return null; // nobody signed in: people read or post as guests
    const { data, error } = await supabase.functions.invoke("feedback-token");
    if (error) throw error;
    return data.token;
  },
});

Another function#

The same pattern works anywhere a function can check who is signed in, such as Cloudflare Workers, Vercel or Netlify functions, or AWS Lambda. A Cloudflare Worker, with the secret stored by wrangler secret put and the ids as variables:

src/worker.js
import { identityToken } from "./identity-token.js";

export default {
  async fetch(request, env) {
    // However your app checks its session
    const user = await currentUser(request, env);
    const keys = {
      secret: env.SWINGBACK_IDENTITY_SECRET,
      secretId: env.SWINGBACK_IDENTITY_SECRET_ID,
      workspaceId: env.SWINGBACK_WORKSPACE_ID,
    };
    const token = user ? await identityToken(user, keys) : null;
    return Response.json({ token }, { headers: { "Cache-Control": "no-store" } });
  },
};

What a function must not do#

  • Sign for an id the request names. The function signs for the user whose session it checked, and nobody else. A function that signs a token for any id it's asked for would let anyone sign in as anyone.
  • Pass an email nobody verified. Swingback links a token's email to the customer who has it, so an address someone typed without confirming it could be another person's.
  • Put the secret in your app. Not in its code, its bundle or a public variable (NEXT_PUBLIC_…, VITE_…, EXPO_PUBLIC_…): only in the function's secrets.

Sign-in without a server (dangerous)#

Your app will be able to name its signed-in user itself, with no token, where an owner turns it on. Nothing will prove who the user is, so it will suit internal tools and prototypes only. Its switch is already under Settings → Sign-in: leave it off until this page documents it.

Search pages, sections and code: a setting, an event, a method.