NodeJS SAP BTP Credential存储REST API身份验证和MTLS

kzmpq1sx  于 2024-01-07  发布在  Node.js
关注(0)|答案(1)|浏览(153)

因此,我使用SAP BTP试用帐户,并试图使一个小节点的JS应用程序绑定到信用存储服务示例。对于试用帐户,只有MTLS认证是可能的密钥和证书。
我用标准的fetch方法尝试了这个方法,但它不能正常工作。
作为参考,我按照这2分钟阅读SAP mtls doc for cred store
他们通过VCAP env变量提供这些值。问题是我没有这个认证的经验,我试图编写代码并认为它是正确的,但我收到的唯一错误是“2023-03- 13 T12:03:30.54+0000 [APP/PROC/WEB/0] ERR请求失败:认证失败。请检查您的凭据并重试”。
这并不能解释太多,有人可以看看我的代码是否正确,并建议修改。
代码:

const express = require('express');
const fetch = require('node-fetch');
const https = require('https');
const app = express();

const port = process.env.PORT || 3000;

const binding = JSON.parse(process.env.VCAP_SERVICES).credstore[0].credentials;
//console.log(binding);

async function fetchWithMtls(url, method, headers, cert, key) {
    try {
        const response = await fetch(url, {
          method,
          headers,
          agentOptions: {
            cert,
            key,
          },
        });
    
        if (!response.ok) {
          let message = `Request failed with status ${response.status}`;
          if (response.status === 401) {
            message = 'Authentication failed. Please check your credentials and try again.';
          }
          throw new Error(message);
        }
    
        return response;
      } catch (error) {
        throw new Error(`Request failed: ${error.message}`);
      }
  }

async function main(){  try {
  const method = 'get';
  const headers = {
    'sapcp-credstore-namespace': 'namespace1',
    'Cache-Control': 'no-cache',
  };

  const response = await fetchWithMtls(`${binding.url}/password?name=${encodeURIComponent('neylux')}`, method, headers, binding.certificate, binding.key);
  const data = await response.json();
  
  console.log('!!!!!!!!!!!!!Response:!!!!!!!!!!!!!!!!!', data);
} catch (error) {
  console.error(error.message);
}

app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});}

main();

字符串

ipakzgxi

ipakzgxi1#

以防万一它会帮助其他人,使用agent而不是agentOptions,就像我这样工作:

const agent = new https.Agent({
    cert: cert,
    key: key
});

字符串
然后fetch调用

fetch(url, {
    method,
    headers,
    agent
  })

相关问题