Skip to main content

Sign users in with OpenID Connect

Use this flow when a person uses your web app and Scenid should know who they are: their permissions apply, journal entries carry their name, and group ACLs are enforced.

Browser ──1 /login──▶ your server ──2 redirect──▶ auth.<domain>/oauth/authorize
│ user signs in, consents
Browser ◀──3 redirect to /callback?code=…──────────────────┘
your server ──4 completeFlow(code)──▶ ID token (+ refresh token)
your server ──5 sdk.asUser(idToken)──▶ token exchange ──▶ Customers / Insights / Files as that user

The SDK implements steps 2 to 5. Your app only needs a /login and a /callback route.

Before you start​

  • Register an app with a Redirect URI matching your callback, for example http://localhost:3000/callback. See Create an app.
  • Generate a service key for that app. User token exchange requires it.
  • The app needs the scopes openid profile email offline_access. Apps created in the admin UI get them by default.

Complete Express example​

server.mjs
import express from 'express'
import session from 'express-session'

import sdk, { initScenid } from '@scenid/cloud-sdk'

import serviceKey from './service-key.json' with { type: 'json' }

initScenid(serviceKey)

const REDIRECT_URI = 'http://localhost:3000/callback'

const app = express()
app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false }))

// 1. Send the user to Scenid
app.get('/login', (req, res) => {
req.session.state = crypto.randomUUID()

const url = sdk.Auth().beginFlow({
redirectUri: REDIRECT_URI,
state: req.session.state
})

res.redirect(url)
})

// 2. Scenid sends the user back with ?code=
app.get('/callback', async (req, res) => {
if (req.query.state !== req.session.state) return res.status(400).send('invalid state')

try {
const { idToken, refreshToken, user } = await sdk.Auth().completeFlow(req.query.code, REDIRECT_URI)

req.session.idToken = idToken
req.session.refreshToken = refreshToken
req.session.user = { sub: user.sub, name: user.name, email: user.email }

res.redirect('/')
} catch (error) {
console.error(error)
res.status(401).send('login failed')
}
})

// 3. Call Scenid as the signed-in user
app.get('/my-customers', async (req, res) => {
if (!req.session.idToken) return res.status(401).send('sign in first')

const customers = sdk.asUser(req.session.idToken).Customers()
const { status, result } = await customers.Entities.list({ entityTypes: ['ou'] })

res.status(status).json(result)
})

app.listen(3000, () => console.log('http://localhost:3000'))

Step by step​

beginFlow​

Builds the authorization URL. Default scope is openid profile email offline_access. Pass scope to change it and always pass a random state to protect against CSRF. There is no PKCE in the SDK flow, the request is authenticated by your server's client secret.

completeFlow​

Exchanges the code for tokens: { idToken, refreshToken, user }. user is the decoded ID token payload (sub, email, name, tenantId, owner, admin, …). The authorization code is single-use and short-lived.

asUser​

sdk.asUser(idToken) exchanges the ID token (RFC 8693 token exchange) for a user access token and caches it per user. Requirements checked by Scenid:

  • The ID token was issued to this app (aud equals your client_id).
  • It belongs to the same tenant as the app.
  • The account is active.

asUser gives you Customers(), Files(), Insights() and Profile(). There is no Auth().

Refresh tokens​

The refresh token lets you get a new ID token without asking the user again (valid 12 hours).

app.use(async (req, res, next) => {
const { idToken, refreshToken } = req.session
if (!idToken) return next()

const { exp } = JSON.parse(Buffer.from(idToken.split('.')[1], 'base64url'))
if (exp * 1000 > Date.now() + 60_000) return next()

try {
const fresh = await sdk.Auth().refreshFlow(refreshToken)
req.session.idToken = fresh.idToken
req.session.refreshToken = fresh.refreshToken ?? refreshToken
} catch {
req.session.destroy(() => res.redirect('/login'))
return
}
next()
})

Logout​

app.get('/logout', (req, res) => {
const { user } = req.session
if (user) sdk.Auth().clearExchangeCache(user.sub)
req.session.destroy(() => res.redirect('/'))
})

clearExchangeCache(sub) removes the cached user tokens of that user. The callback above stores sub in the session for this purpose.

Errors​

ErrorMeaning
auth/complete-flow-failed: 400 oauth/redirect-uri-mismatchredirectUri differs from the one in the app
auth/complete-flow-failed: 400 oauth/code-expired or oauth/invalid-codeCode was used twice or is too old
auth/exchange-failed: 403 oauth/service-key-not-provisionedGenerate a service key for the app
auth/exchange-failed: 403 oauth/token-audience-mismatchID token came from a different app

More in Troubleshooting.