mocksaml/pages/api/saml/sso.ts

48 lines
1.5 KiB
TypeScript
Raw Normal View History

2022-02-21 05:52:12 +00:00
import type { NextApiRequest, NextApiResponse } from 'next';
2022-02-22 05:36:06 +00:00
import { createResponseForm, createResponseXML, extractSAMLRequestAttributes } from 'utils';
2022-02-21 05:52:12 +00:00
import { User } from 'types';
2022-02-22 05:36:06 +00:00
import config from '../../../lib/env';
2022-02-21 14:31:47 +00:00
import { signResponseXML } from 'utils/response';
import { fetchPrivateKey, fetchPublicKey } from 'utils/certificate';
2022-02-21 05:52:12 +00:00
2022-02-22 05:36:06 +00:00
export default async function handler(req: NextApiRequest, res: NextApiResponse<string>) {
2022-02-21 05:52:12 +00:00
switch (req.method) {
case 'GET':
return await processSAMLRequest();
default:
return res.status(405).end(`Method ${req.method} Not Allowed`);
}
async function processSAMLRequest() {
const relayState = <string>req.query.RelayState;
const samlRequest = <string>req.query.SAMLRequest;
2022-02-22 05:35:42 +00:00
const { id, audience, acsUrl, providerName } = await extractSAMLRequestAttributes(samlRequest);
2022-02-21 05:52:12 +00:00
2022-02-22 05:35:42 +00:00
const idpIdentityId = audience;
// const audience = config.entityId;
2022-02-21 05:52:12 +00:00
const user: User = {
id: '1',
email: 'kiran@boxyhq.com',
firstName: 'Kiran',
lastName: 'K',
};
2022-02-21 15:36:25 +00:00
const xml = await createResponseXML({
2022-02-21 05:52:12 +00:00
idpIdentityId: idpIdentityId,
audience: audience,
acsUrl: acsUrl,
user: user,
});
2022-02-21 14:31:47 +00:00
const signingKey = await fetchPrivateKey();
const publicKey = await fetchPublicKey();
const xmlSigned = await signResponseXML(xml, signingKey, publicKey);
2022-02-21 16:07:39 +00:00
const encodedSamlResponse = Buffer.from(xmlSigned).toString('base64');
2022-02-21 05:52:12 +00:00
const html = createResponseForm(relayState, encodedSamlResponse, acsUrl);
res.send(html);
}
2022-02-22 05:36:06 +00:00
}