使用本机 Node.JS 代码获得 WSO2 access_token

Use native Node.JS code to get a WSO2 access_token

我一直在尝试使用 Node 8 中的本机 Node.JS 代码来使用我的客户端 ID 和客户端密码从 WSO2 获取访问令牌。 我收到以下错误:不支持的客户端身份验证方法!

这是我的代码:

const querystring = require('querystring');
const https = require('https');

var postData = querystring.stringify({
  'grant_type' : 'client_credentials'
});

var options = {
  hostname: 'api.somedomain.com',
  port: 443,
  path: '/token',
  method: 'POST',
  headers: {
     'Content-Type': 'application/x-www-form-urlencoded',
     'Content-Length': postData.length
  }
};

var req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (data) => {
     process.stdout.write(data);
  });
});

req.on('error', (err) => {
  console.error(err);
});

req.write(postData);
req.end();

当我尝试为客户端 ID 和客户端密码包含另一个选项参数 'auth' 时,它告诉我 "TypeError: First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object."

非常感谢任何有关如何完成这项工作的帮助。

看起来您在请求中缺少 Authorization header。我不是 javascript/node 方面的专家,但在 headers 部分中添加 Authorization header 后令牌生成工作正常,如下所示。我使用 localhost 进行测试。

var auth = 'Basic ' + Buffer.from("nM_ftrK2pjoBW4JofE21xI1cP0Ya" + ':' + "jmFJIgC5QMDkU_HxQKiDUbp5UAca").toString('base64');

var options = {
    hostname: 'localhost',
    port: 8243,
    path: '/token',
    method: 'POST',

    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': postData.length,
        'Authorization': auth
    }
};

在调用令牌端点以获取 access_token.

时,应随令牌请求一起传递正确的值 (Authorization : Basic Base64(consumer-key:consumer-secret))