OpenMax
Free Trial

End-to-end examples

Complete sign-in examples in Node.js (Express + jose) and Go: start authorization, exchange the token in the callback, verify the id_token, bind accounts, and block expired sessions.

End-to-end examples

This page gives two pieces of server code you can adapt: the Node.js version covers the whole sign-in flow, and the Go version only covers the callback token exchange and id_token verification. Both are written for opening in a "new tab (top level)"; when embedded, do not redirect inside the iframe; use requestAuthCode from "Sign-in when embedded" instead.

Node.js (Express + jose)

import crypto from "node:crypto";
import { createRemoteJWKSet, jwtVerify } from "jose";

const ISSUER = process.env.OPENMAX_ISSUER;            // OpenMax address: https://openmax.com
const APP_ID = process.env.OPENMAX_APP_ID;
const APP_SECRET = process.env.OPENMAX_APP_SECRET;    // backend only
const REDIRECT_URI = "https://my-app.example.com/auth/openmax/callback"; // must match the manifest byte for byte
const ALLOWED_ORG_IDS = new Set(process.env.OPENMAX_ORG_IDS.split(",")); // organization app = the one organization it belongs to
const JWKS = createRemoteJWKSet(new URL(`${ISSUER}/api/v1/apps/jwks`));
const rnd = () => crypto.randomBytes(32).toString("base64url");

// inside an iframe this is a third-party cookie
const FLOW_COOKIE = { httpOnly: true, secure: true, sameSite: "none", partitioned: true, maxAge: 600_000 };

function safeReturnTo(p) {
  if (typeof p !== "string" || !p.startsWith("/") || p.startsWith("//") || p.startsWith("/\\")) return "/";
  if (/[\\\u0000-\u001f\u007f]/.test(p) || p.split(/[?#]/)[0].split("/").includes("..")) return "/";
  return p;
}

// 1) No session: at top level (new tab) the frontend navigates its own window here (do not come automatically when a failure marker is present); when embedded do not come here, use requestAuthCode from "Sign-in when embedded"
app.get("/auth/openmax/login", async (req, res) => {
  const flow = { id: rnd(), state: rnd(), nonce: rnd(), verifier: rnd(),
                 returnTo: safeReturnTo(req.query.return_to) };
  await flows.put(flow.id, flow, { ttlSeconds: 600 });      // stored server-side, single use
  res.cookie("app_login_flow", flow.id, FLOW_COOKIE);
  const challenge = crypto.createHash("sha256").update(flow.verifier).digest("base64url");
  const q = new URLSearchParams({
    response_type: "code", client_id: APP_ID, redirect_uri: REDIRECT_URI,
    state: flow.state, nonce: flow.nonce,
    code_challenge: challenge, code_challenge_method: "S256",
    scope: "org:me:read org:me.email:read",
  });
  res.redirect(`${ISSUER}/api/v1/apps/authorize?${q}`);
});

// 2) Callback: GET {redirect_uri}?code&state&iss  or  ?error&error_description&iss[&state]   (state only if it was valid)
app.get("/auth/openmax/callback", async (req, res) => {
  const flow = await flows.take(req.cookies.app_login_flow);  // deleted when taken
  res.clearCookie("app_login_flow", FLOW_COOKIE);
  const fail = (why) => res.redirect(`/?login_error=${encodeURIComponent(why)}`); // home page with a marker does not auto-retry
  if (!flow) return fail("state");
  if (req.query.iss !== ISSUER) return fail("state");
  const s = String(req.query.state ?? "");
  if (s.length !== flow.state.length ||
      !crypto.timingSafeEqual(Buffer.from(s), Buffer.from(flow.state))) return fail("state");
  if (req.query.error) return fail(String(req.query.error));   // login_required / access_denied / ...

  const r = await fetch(`${ISSUER}/api/v1/apps/token`, {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({
      grant_type: "authorization_code", code: String(req.query.code),
      redirect_uri: REDIRECT_URI, code_verifier: flow.verifier,
      client_id: APP_ID, client_secret: APP_SECRET,
    }),
  });
  if (!r.ok) return fail("token");
  const tok = await r.json();
  const { payload } = await jwtVerify(tok.id_token, JWKS, {
    issuer: ISSUER, audience: APP_ID, algorithms: ["RS256"], clockTolerance: 30,
  });
  if (payload.nonce !== flow.nonce || payload.sub !== payload.member_id) return fail("token");
  if (!ALLOWED_ORG_IDS.has(payload.org_id)) return fail("org");      // fixed organizations: members of other organizations are not let in

  // Account binding: only (issuer, org_id, member_id) counts; email is for display only, never used to auto-link existing accounts (see "Integrating existing systems")
  let account = await accounts.findByBinding(ISSUER, payload.org_id, payload.member_id);
  if (!account) {
    if (POLICY.provisioning !== "auto") return fail("not_bound");    // manual pre-binding: show "Please contact your admin to get access"
    account = await accounts.provision({                            // one transaction: account + binding + default role + default projects;
      issuer: ISSUER, orgId: payload.org_id, memberId: payload.member_id, // binding has a unique constraint, so two tabs entering for the first time create only one
      name: payload.name, email: payload.email,
      role: POLICY.defaultRole, projects: POLICY.defaultProjects,    // do not add to all historical projects
    });
  }
  if (account.disabled) return fail("account_disabled");            // disabled inside the app: do not retry

  await regenerateSession(req);                                      // new session ID, prevents session fixation
  req.session.user = { accountId: account.id, orgId: payload.org_id, memberId: payload.member_id };
  // session lifetime cap = token expiry (15 minutes); on expiry requireSession blocks it and re-authorizes
  req.session.openmax = { access_token: tok.access_token, expires_at: payload.exp * 1000 };
  if (tok.refresh_token) await saveRefreshToken(account.id, tok.refresh_token); // offline_access only; store the new one on every refresh
  res.redirect(flow.returnTo === "/" ? POLICY.landingPath : flow.returnTo); // only use the path stored server-side
});

// 3) Every business request goes through here first: expired sessions are always blocked and discarded, then re-authorized
function requireSession(req, res, next) {
  const s = req.session.openmax;
  if (req.session.user && s && Date.now() < s.expires_at - 30_000) return next();
  req.session.user = null; req.session.openmax = null;               // expired / incomplete sessions are discarded
  if (req.get("accept")?.includes("application/json"))
    return res.status(401).json({ error: "reauth_required" });       // API: the frontend then does a full-page navigation to authorize
  if (req.query.login_error || req.query.signed_out)
    return res.status(401).send(loginHelpPage(req.query.login_error)); // failure / sign-out marker present: only show a "Sign in again" button
  res.redirect(`/auth/openmax/login?return_to=${encodeURIComponent(req.originalUrl)}`); // seamless re-authorization
}

// 4) Re-check identity (optional): 200 only means it is valid right now and does not extend expires_at — re-check ≠ renewal
const me = await fetch(`${ISSUER}/api/v1/me`, {
  headers: { Authorization: `Bearer ${req.session.openmax.access_token}` },
});
if (me.status === 401) { /* authorization gone (disabled / uninstalled / member left / expired): discard the session, show no-access or authorize once more */ }
if (me.status === 403) { /* missing scope: show no-access, do not retry */ }

flows, accounts, POLICY, regenerateSession and loginHelpPage are your own storage, the configuration of your integration policy table (see "Integrating existing systems"), and session utilities (such as req.session.regenerate in express-session).

  • Session cookies inside an iframe also need Secure; HttpOnly; SameSite=None; Partitioned, with maxAge no more than 15 minutes (or simply use a session cookie).
  • Do not put requireSession on /auth/openmax/* or the callback itself.
  • Frontend (top level / new tab): with no session and no login_error / signed_out in the URL, set location.href = "/auth/openmax/login?return_to=" + encodeURIComponent(location.pathname + location.search); do the same full-page navigation when an API returns reauth_required.
  • When embedded, do not navigate the iframe: ask the host for an authorization code instead; for the backend API see the example in "Sign-in when embedded".

Go (callback token exchange + id_token verification)

import "github.com/coreos/go-oidc/v3/oidc"

keys := oidc.NewRemoteKeySet(ctx, issuer+"/api/v1/apps/jwks")
verifier := oidc.NewVerifier(issuer, keys, &oidc.Config{ClientID: appID, SupportedSigningAlgs: []string{"RS256"}})

func callback(w http.ResponseWriter, r *http.Request) {
    flow, ok := takeFlow(r)                 // take and delete by the flow cookie
    q := r.URL.Query()
    if !ok || q.Get("iss") != issuer ||
        subtle.ConstantTimeCompare([]byte(q.Get("state")), []byte(flow.State)) != 1 {
        http.Redirect(w, r, "/?login_error=state", http.StatusFound); return
    }
    if e := q.Get("error"); e != "" {
        http.Redirect(w, r, "/?login_error="+url.QueryEscape(e), http.StatusFound); return
    }
    resp, err := http.PostForm(issuer+"/api/v1/apps/token", url.Values{
        "grant_type": {"authorization_code"}, "code": {q.Get("code")},
        "redirect_uri": {redirectURI}, "code_verifier": {flow.Verifier},
        "client_id": {appID}, "client_secret": {appSecret},
    })
    // check err / resp.StatusCode, decode {access_token, id_token, expires_in, refresh_token, user}
    idt, err := verifier.Verify(r.Context(), tok.IDToken)   // signature, iss, aud, exp
    if err != nil { /* fail */ }
    var claims struct {
        MemberID string `json:"member_id"`
        OrgID    string `json:"org_id"`
        Name     string `json:"name"`
        Email    string `json:"email"`
        Nonce    string `json:"nonce"`
    }
    if idt.Claims(&claims) != nil || claims.Nonce != flow.Nonce || idt.Subject != claims.MemberID { /* fail */ }
    if !allowedOrgIDs[claims.OrgID] { /* fail: not an organization served by this deployment */ }
    // look up the binding by (issuer, claims.OrgID, claims.MemberID) → handle unbound / disabled per the integration policy table
    // create the session, expiry = idt.Expiry (15 minutes), redirect to flow.ReturnTo
}

Generating PKCE in Go: verifier := oauth2.GenerateVerifier(), oauth2.S256ChallengeOption(verifier) (golang.org/x/oauth2 ≥ 0.13).