为了使用另一个 API 对我的节点服务器 (Express JS) 进行身份验证,必须在 POST 请求中发送单独的 header 。
引自文档:
You need to send a X-Authorization-Ahoi header with this request. The header value is an encoded JSON string that consists of the
<INSTALLATION_ID>
, a random 16-character string as nonce and the current date in ISO 8601 format.
文档中的示例:
{
"installationId":"<INSTALLATION_ID>",
"nonce":"0wYWLarLDBrWU7B2I1Go4A==",
"timestamp":"2018-11-01T11:32:44.413Z"
}
在 API 的文档中,给出了以下 Java 示例,我尝试用 Javascript 重现该示例。
String installationId = <INSTALLATION_ID>;
// create nonce
byte[] nonce = new byte[16];
SecureRandom.getInstanceStrong().nextBytes(nonce);
String nonceBase64Enc = Base64.getEncoder().encodeToString(nonce);
// create timestamp
String timeStr = Instant.now().toString();
// create json string
String xAuthAhoiJson = String.format("{\"installationId\":\"%s\",\"nonce\":\"%s\",\"timestamp\":\"%s\"}",
installationId, nonceBase64Enc, timeStr);
// encode encrypted header value
String XAUTH_AHOI_BASE64_URL_ENC = Base64.getUrlEncoder().withoutPadding()
.encodeToString(xAuthAhoiJson.getBytes( StandardCharsets.UTF_8 ));
这是我一直在尝试做的事情:
const installationId = '<EXAMPLE_INSTALLATIONID>';
const nonce_tmp = crypto.randomBytes(16);
const nonce = nonce_tmp.toString('base64');
const date = new Date();
const timestamp = date.toISOString();
const xAuthAhoiJson = JSON.stringify({installationId, nonce, timestamp});
const XAUTH_AHOI_BASE64_URL_ENC = base64url.encode(xAuthAhoiJson);
const url = 'https://banking-sandbox.starfinanz.de/auth/v1/oauth/token?grant_type=client_credentials';
const options = { headers:
{ 'Authorization': 'Basic ' + Buffer.from(credentials).toString('base64'),
'X-Authorization-Ahoi': XAUTH_AHOI_BASE64_URL_ENC }
};
request.post(url, options, function (e, r, b) { console.log(b); });
对于 POST 请求,我使用 request-package . 对于 Base64 URL Safe 中的编码,我使用 base64url-package . 执行 POST 请求时,我收到以下消息:
{
"timestamp": 1543229480764,
"status": 400,
"error": "Bad Request",
"message": "Nonce is invalid.",
"path": "/auth/v1/oauth/token"
}
现在我的问题是:创建 Nonce 有什么问题,我该如何解决? 还是我要向其发送 POST 请求的 API?
最佳答案
您只是忘记将 nonceBase64Enc
转换为字符串。您已经在 java 中完成了该操作,但没有在 javascript 中完成。
只需在 nonceBase64Enc
的末尾添加 .toString('hex');
Example : const nonceBase64Enc = Buffer.from(nonce, 'base64').toString('hex');
你现在完成了! 🎉🍾
关于javascript - 在 ExpressJS 中创建身份验证 header 。 Java 到 Javascript 的翻译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53480894/