首页 > 解决方案 > 在 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?

标签: javascriptjavaexpresspostheader

解决方案


您只是忘记将其转换nonceBase64Enc为字符串。您已经在 java 中做到了这一点,但在 javascript 中却没有。

只需.toString('hex');在末尾添加nonceBase64Enc

示例: const nonceBase64Enc = Buffer.from(nonce, 'base64').toString('hex');

你现在完成了!


推荐阅读