|
// Naver Cloud Platform API Pre-request Script |
|
// https://api.ncloud-docs.com/docs/common-ncpapi |
|
|
|
const accessKey = pm.environment.get('NCP_ACCESS_KEY'); |
|
const secretKey = pm.environment.get('NCP_SECRET_KEY'); |
|
|
|
if (!accessKey || !secretKey) { |
|
throw new Error('Missing NCP_ACCESS_KEY or NCP_SECRET_KEY in environment'); |
|
} |
|
|
|
// timestamp in milliseconds |
|
const timestamp = Date.now().toString(); |
|
const method = pm.request.method; |
|
|
|
// const url = pm.request.url.getPathWithQuery(); |
|
|
|
let url = pm.request.url.getPath(); |
|
|
|
// encode query params - only encode non-ASCII characters |
|
const queryParams = pm.request.url.query.all(); |
|
if (queryParams.length > 0) { |
|
const encodedParams = queryParams |
|
.filter(param => !param.disabled) |
|
.map(param => { |
|
// Function to encode only non-ASCII characters |
|
const encodeNonAscii = (str) => { |
|
return str.replace(/[^\x00-\x7F]/g, (char) => |
|
encodeURIComponent(char) |
|
); |
|
}; |
|
|
|
const key = encodeNonAscii(param.key); |
|
const value = param.value ? encodeNonAscii(param.value) : ''; |
|
return key + '=' + value; |
|
}) |
|
.join('&'); |
|
|
|
if (encodedParams) { |
|
url = url + '?' + encodedParams; |
|
} |
|
} |
|
|
|
const space = ' '; |
|
const newLine = '\n'; |
|
const message = `${method} ${url}\n${timestamp}\n${accessKey}`; |
|
|
|
const hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, secretKey); |
|
hmac.update(method); |
|
hmac.update(space); |
|
hmac.update(url); |
|
hmac.update(newLine); |
|
hmac.update(timestamp); |
|
hmac.update(newLine); |
|
hmac.update(accessKey); |
|
|
|
const hash = hmac.finalize(); |
|
const signature = hash.toString(CryptoJS.enc.Base64); |
|
|
|
pm.request.headers.upsert({ |
|
key: "x-ncp-apigw-timestamp", |
|
value: timestamp |
|
}); |
|
|
|
pm.request.headers.upsert({ |
|
key: "x-ncp-iam-access-key", |
|
value: accessKey |
|
}); |
|
|
|
pm.request.headers.upsert({ |
|
key: "x-ncp-apigw-signature-v2", |
|
value: signature |
|
}); |
|
|
|
if (pm.environment.get('NCP_AUTH_DEBUG') === 'true') { |
|
console.log("=== Naver Cloud API Signature ==="); |
|
console.log("Method:", method); |
|
console.log("URL (encoded):", url); |
|
console.log("Timestamp:", timestamp); |
|
console.log("Access Key:", accessKey); |
|
console.log("Message for signing:"); |
|
console.log(message); |
|
console.log("Signature:", signature); |
|
} |