Skip to main content

Verify tokens and protect routes

If your own API accepts Scenid tokens (from a browser app, from another service) you must verify them. The SDK can do this using the public keys of your Scenid tenant.

Verify a token​

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

initScenid(serviceKey)

const payload = await sdk.Auth().verify(idToken)
// { sub, tenantId, email, name, owner, admin, exp, iss, … }

verify checks:

  1. the RS256 signature against the JWKS in your service key (jwks_uri, cached for one hour);
  2. that iss equals the issuer in the service key;
  3. that the token is not expired.

It does not check aud. Do that yourself if you need to make sure a token was issued to your app.

Possible errors: auth/invalid-signature, auth/invalid-issuer, auth/token-expired, auth/jwks-key-not-found, auth/jwks-fetch-failed, sdk/invalid-token-format. Only RS256 is supported.

Express middleware​

import express from 'express'

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

initScenid(serviceKey)

const app = express()
app.use(sdk.Auth().middleware())

The middleware is soft. It always calls next(). If a valid Authorization: Bearer token is present it sets:

TokenSets
A user tokenreq.user (the payload)
A service token (token_type: 'service')req.serviceClient = { clientId, tenantId, scope, clientName, isServiceClient: true }

Invalid or missing tokens leave both undefined. You decide per route what is required, using the guards below.

Guards​

Guards take the request (or any object with user and serviceClient), return the identity and throw AuthenticationError (httpCode: 401) if the check fails.

import {
AuthenticationError,
checkIsUser,
checkIsAdmin,
checkIsOwner,
checkIsService,
checkHasClaim,
checkIsProductUser,
oneOf
} from '@scenid/cloud-sdk'

app.get('/me', (req, res) => {
const user = checkIsUser(req)
res.json({ name: user.name })
})

// Either a service client or an admin user
app.post('/admin/sync', async (req, res) => {
await oneOf(req, [checkIsService, checkIsAdmin])
res.json({ started: true })
})

// Central error handler
app.use((error, req, res, next) => {
if (error instanceof AuthenticationError) return res.sendStatus(error.httpCode)
next(error)
})
GuardPasses when
checkIsUser(ctx)ctx.user exists. Returns it
checkIsOwner(ctx)user.owner === true
checkIsAdmin(ctx)user is owner or user.admin === true
checkIsService(ctx)ctx.serviceClient.isServiceClient. Returns the client
checkHasClaim(ctx, 'a.b.c')owner, or the claim at that dotted path is true
checkHasClaims(ctx, [paths])owner, or any listed claim is true
checkIsProductUser(ctx, 'customers')user has customers.use or customers.admin
checkIsProductAdmin(ctx, 'customers')user has customers.admin
oneOf(ctx, [guards])async. Returns the result of the first guard that passes. Rethrows anything but AuthenticationError
hasResourcePermission(ctx, allowed)boolean. allowed is [{ type: 'user' | 'group', id }], matched against user.sub and user.userGroups
checkHasResourcePermission(ctx, allowed)throwing variant