mocksaml/pages/api/saml/sso.ts

52 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-21 15:36:25 +00:00
import { createResponseForm, createResponseXML } from 'utils';
2022-02-21 05:52:12 +00:00
import { User } from 'types';
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
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<string>
) {
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;
const idpIdentityId = config.entityId;
const audience = config.entityId;
const acsUrl = 'http://localhost:3000/sso/acs'; // TODO: Fetch acsUrl from SAMLRequest
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 05:52:12 +00:00
2022-02-21 14:31:47 +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);
}
}