javascript - 在 ExpressJS 中创建身份验证标头。Java 到 Javascript 的翻译
问题描述
为了使用另一个 API 对我的节点服务器 (Express JS) 进行身份验证,必须在 POST 请求中发送单独的标头。
从文档中引用:
您需要随此请求发送 X-Authorization-Ahoi 标头。标头值是一个编码的 JSON 字符串,由
<INSTALLATION_ID>
、一个随机的 16 个字符的随机字符串和 ISO 8601 格式的当前日期组成。
文档中的示例:
{
"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 中却没有。
只需.toString('hex');
在末尾添加nonceBase64Enc
示例: const nonceBase64Enc = Buffer.from(nonce, 'base64').toString('hex');
你现在完成了!
推荐阅读
- git - 如何在不检查的情况下将另一个分支重置为原点?
- ios - 如何在我的自定义键盘扩展中获取当前和正确的宽度
- node.js - 异步 .mjs 直接调用时有效,从另一个 .mjs 调用时失败
- python - 如何在 google colab 中管理 gpu RAM?
- python - Python Django AttributeError 'str' 对象没有属性 'user_name'
- flask - Flask-CKEditor - 错误代码:编辑器元素冲突
- r - 将两条 rle 行应用到数据集中时发生“无效的 'rle' 结构”
- ios - 我应该如何确定 UIKit 将打开哪个场景,以便我可以在正确的窗口中设置我的 UI?(iOS 13+)
- .net - dotNetRDF 无法加载 System.EnterpriseServices
- javascript - 如何在 next.config.js 文件中组合几个插件?