Skip to main content

NodeJs Tutorial

Welcome to the NodeJs setup tutorial! This tutorial will guide you through the steps to integrate AuthSezam with NodeJs.

I - Technical Prerequisites

To set up OIDC on a NodeJs, you need :

  • A functional NodeJs server running on HTTPS
  • Basic knowledge of NodeJs
  • Access to the following variables:
    • $oidcHost: OIDC domaine*
    • $clientId: OIDC client ID*
    • $clientSecret: OIDC client secret*
    • $realm : OIDC realm name*

*Provided by us in a separate document

II - Installing the Components

npm install openid-client

III - Configuring the Components

  • In your .env file, add the variables below:
CLIENT_ID=$clientId
CLIENT_SECRET=$clientSecret
REALM=$realm
OIDC_HOST=$oidcHost

IV - Testing and Validation

  • Un exemple de code fonctionnelle avec un serveur http nodejs
const http = require('http');
const url = require('url');
const { Issuer, generators } = require('openid-client');
require('dotenv').config();

const port = process.env.PORT;
const clientId = process.env.CLIENT_ID;
const clientSecret = process.env.CLIENT_SECRET;
const realm = process.env.REALM;
const oidcHost = process.env.OIDC_HOST;
const serveurHost = process.env.SERVEUR_HOST;

async function initialize() {
const openIdIssuer = await Issuer.discover(`https://${oidcHost}/realms/${realm}/.well-known/openid-configuration`);
const code_verifier = generators.codeVerifier();
const code_challenge = generators.codeChallenge(code_verifier);

const client = new openIdIssuer.Client({
client_id: clientId,
client_secret: clientSecret,
redirect_uris: [`http://${serveurHost}:${port}/callback`],
response_types: ['code'],
});

const server = http.createServer(async (req, res) => {
const parsedUrl = url.parse(req.url);
const path = parsedUrl.pathname;
const query = querystring.parse(parsedUrl.query);

if (path === '/') {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<a href="/login">Login with AuthSezam</a>');
} else if (path === '/login') {
const authorizationUrl = client.authorizationUrl({
scope: 'openid profile email',
code_challenge,
code_challenge_method: 'S256',
});
res.writeHead(302, { 'Location': authorizationUrl });
res.end();
} else if (path === '/callback') {
const authorizationCode = query.code;
if (authorizationCode) {
try {
const tokenSet = await client.callback(`http://${serveurHost}:${port}/callback`, { code: authorizationCode }, { code_verifier });
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
accessToken: tokenSet.access_token,
idToken: tokenSet.id_token,
decodedIdToken: tokenSet.claims(),
}, null, 2));
} catch (err) {
console.error('Error exchanging authorization code for tokens:', err);
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Authentication failed');
}
} else {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('No authorization code received');
}
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});

server.listen(port, () => {
console.log(`Server is listening on port ${port}`);
});
}

initialize().catch((err) => {
console.error('Failed to initialize the server:', err);
});