Nicolas Alejandro Vaquero
12/20/2023, 11:35 AMNicolas Alejandro Vaquero
12/20/2023, 11:36 AMimport { Request, sign } from "aws4";
// ...
const getCredentials = async (
roleArn?: string
): Promise<AwsCredentialIdentity> =>
roleArn ? getRoleCredentials(roleArn) : fromEnv()();
export const aws4SignAuth = async (
apiEndpoint: string,
requestOptions: Omit<Request, "host" | "path" | "headers">,
roleArn?: string
): Promise<express.RequestHandler> => {
const parsedUrl = new URL(apiEndpoint);
const credentials = await getCredentials(roleArn);
return (req, res, next) => {
const options: Request = {
host: parsedUrl.host,
path: parsedUrl.pathname + req.path,
headers: {},
...requestOptions,
...(req.method === "POST"
? {
body: String(req.body),
headers: { "Content-Type": "application/json" },
}
: {}),
};
const signed = sign(options, credentials);
Object.assign(req.headers, signed.headers);
next();
};
};
Yousaf Nabi (pactflow.io)
Nicolas Alejandro Vaquero
01/09/2024, 1:51 PMconst getCredentials = async (
roleArn?: string
): Promise<AwsCredentialIdentity> =>
roleArn ? getRoleCredentials(roleArn) : fromEnv()();
export const aws4SignAuth = async (
apiEndpoint: string,
requestOptions: Omit<Request, "host" | "path" | "headers">,
roleArn?: string
): Promise<express.RequestHandler> => {
const parsedUrl = new URL(apiEndpoint);
const credentials = await getCredentials(roleArn);
return (req, res, next) => {
const body =
req.body instanceof Object
? JSON.stringify(req.body)
: String(req.body);
const options: Request = {
host: parsedUrl.host,
path: parsedUrl.pathname + req.path,
headers: {},
...requestOptions,
...(req.method === "POST"
? {
body: Buffer.from(body),
headers: {
...req.headers,
host: parsedUrl.host,
},
}
: {}),
};
const signed = sign(options, credentials);
Object.assign(req.headers, signed.headers);
next();
};
};