mocksaml/pages/api/saml/auth.ts
Deepak Prabhakara 331c3cf318
Switch to saml20 (#21)
* Use boxyhq/saml20

* use sign from saml20

* cleaned up GetKeyInfo

* cleaned up getPublicKeyPemFromCertificate

* cleaned up node-forge

* use hasValidSignature from saml20

* cleanup and update saml20 to the beta version

* throw an error if signature is not valid

* updated saml20
2022-04-26 18:02:12 +01:00

46 lines
1.3 KiB
TypeScript

import { createHash } from 'crypto';
import config from 'lib/env';
import type { NextApiRequest, NextApiResponse } from 'next';
import type { User } from 'types';
import { createResponseXML, signResponseXML } from 'utils';
import saml from '@boxyhq/saml20';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === 'POST') {
const { email, audience, acsUrl, id, relayState } = req.body;
if (!email.endsWith('@example.com') && !email.endsWith('@example.org')) {
res.status(403).send(`${email} denied access`);
}
const userId = createHash('sha256').update(email).digest('hex');
const userName = email.split('@')[0];
const user: User = {
id: userId,
email,
firstName: userName,
lastName: userName,
};
const xml = await createResponseXML({
idpIdentityId: config.entityId,
audience,
acsUrl,
samlReqId: id,
user: user,
});
const xmlSigned = await signResponseXML(xml, config.privateKey, config.publicKey);
const encodedSamlResponse = Buffer.from(xmlSigned).toString('base64');
const html = saml.createPostForm(acsUrl, relayState, {
name: 'SAMLResponse',
value: encodedSamlResponse,
});
res.send(html);
} else {
res.status(405).send(`Method ${req.method} Not Allowed`);
}
}