签名认证相关文档
Java 访问非匿名 HTTP 函数示例
Python 访问非匿名 HTTP 函数示例
NodeJS 访问非匿名 HTTP 函数示例
PHP 访问非匿名 HTTP 函数示例
"use strict";
const https = require("https");
const crypto = require("crypto");
const AK = "YOUR_AK";
const SK = "YOUR_SK";
const HOST_NAME = "xxxxx.cn-beijing.fcapp.run";
const PATH = "/list";
const METHOD = "GET";
exports.handler = async (event, context, callback) => {
const date = new Date().toUTCString();
const headers = {
"content-type": "application/json",
//"x-fc-security-token": "FOR_STS_SECURITY_TOKEN",
date: date,
host: HOST_NAME,
};
const signature = signString(
composeStringToSign(METHOD, PATH, headers, {
a: "b" }),
SK
);
const options = {
hostname: HOST_NAME,
port: 443,
path: PATH + "?a=b",
method: METHOD,
headers: {
...headers,
Authorization: `FC ${
AK}:${
signature}`,
},
};
const req = https.request(options, (res) => {
console.log(`statusCode: ${
res.statusCode}`);
res.on("data", (d) => {
console.log(d.toString());
callback(null, res.statusCode);
});
});
req.on("error", (error) => {
console.error(error);
});
req.end();
};
function buildCanonicalHeaders(headers, prefix) {
var list = [];
var keys = Object.keys(headers);
var fcHeaders = {
};
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
var lowerKey = key.toLowerCase().trim();
if (lowerKey.startsWith(prefix)) {
list.push(lowerKey);
fcHeaders[lowerKey] = headers[key];
}
}
list.sort();
var canonical = "";
for (let i = 0; i < list.length; i++) {
const key = list[i];
canonical += `${
key}:${
fcHeaders[key]}\n`;
}
return canonical;
}
function composeStringToSign(method, path, headers, queries) {
const contentMD5 = headers["content-md5"] || "";
const contentType = headers["content-type"] || "";
const date = headers["date"];
const signHeaders = buildCanonicalHeaders(headers, "x-fc-");
var str = `${
method}\n${
contentMD5}\n${
contentType}\n${
date}\n${
signHeaders}${
path}`;
if (queries) {
var params = [];
Object.keys(queries).forEach(function (key) {
var values = queries[key];
var type = typeof values;
if (type === "string") {
params.push(`${
key}=${
values}`);
return;
}
if (Array.isArray(values)) {
queries[key].forEach(function (value) {
params.push(`${
key}=${
value}`);
});
}
});
params.sort();
str += "\n" + params.join("\n");
}
return str;
}
function signString(source, secret) {
const buff = crypto
.createHmac("sha256", secret)
.update(source, "utf8")
.digest();
return Buffer.from(buff, "binary").toString("base64");
}