Talon Auth integrates with Express as a request handler middleware. Wrap verifier.verifyHeader() in a middleware function to protect any route.
Install the packages:
npm install express talon-auth
npm install --save-dev @types/express
Create a verifier with your app ID from the Talon dashboard:
import { createVerifier } from 'talon-auth'
const verifier = createVerifier({ appId: '[your-app-id]' })
Wrap verifier.verifyHeader() in a standard Express RequestHandler. On success, attach the user to res.locals so downstream handlers can access it. On failure, respond with 401:
const authenticate: express.RequestHandler = async (req, res, next) => {
try {
const { user } = await verifier.verifyHeader(req.headers.authorization!)
res.locals.user = user
next()
} catch {
res.status(401).json({ error: 'Unauthorized' })
}
}
Then pass the middleware to any route that requires authentication:
app.get('/message', authenticate, (req, res) => {
res.json({ message: `Hello ${res.locals.user.email}!` })
})
The example below serves an HTML page that loads the <talon-login> web component, authenticates the user in the browser, then calls a /message endpoint that verifies the JWT via the authenticate middleware and returns a personalized greeting.