javascript 通过节点获取检索OAuth2令牌

svujldwt  于 2023-01-16  发布在  Java
关注(0)|答案(3)|浏览(108)

问题是我正在尝试检索OAuth2令牌。由于request已被弃用,因此我使用node-fetch。虽然我可以让它与request一起使用,但无法与node-fetch一起使用。
我在这里读了很多帖子,但似乎没有一个真正给予一个一致的答案,实际上工作。我承认,我只是看起来不够好。也可能是复杂的,我 Package 在一个测试,但它不像是由于我得到的错误信息的情况。
下面是可以正常工作的代码(注意,我不得不修改细节来保护内部URL):

var request = require("request");

var options = {
  method: "POST",
  url: "https://some-url/realms/my-realm/protocol/openid-connect/token",
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
  form: {
    username: "JeffUser",
    password: "jeff-password",
    grant_type: "password",
    client_id: "jeff-client",
    client_secret: "jeff-client"
  }
};

request(options, function(error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
})

这样就成功了,我得到了令牌。下面是我在node-fetch中尝试的东西( Package 在测试中),但失败了:

const assert = require("chai").assert;
const fetch = require("node-fetch")

describe("Test API", function() {
  let api_token = "";

  it("gets a token", async function() {
    api_token = await fetch("https://some-url/realms/my-realm/protocol/openid-connect/token", {
      method: "post",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      form: {
        username: "JeffUser",
        password: "jeff-password",
        grant_type: "password",
        client_id: "jeff-client",
        client_secret: "jeff-client"
      }
    }).then (response => {
      return response.json();
    });

    console.log(token);
  });
});

这里发生的是我从测试中得到了以下输出:

{
  error: 'invalid_request',
  error_description: 'Missing form parameter: grant_type'
}

我试着按照一些搜索的建议将form更改为body,但似乎没有任何效果。我试着按照一些其他搜索的建议将form: { }数据 Package 为JSON.stringify(),但也导致报告相同的错误。

b1zrtrql

b1zrtrql1#

这要感谢@CBroe,他在评论中给了我答案。我会把解决方案放在这里,供其他遇到这个问题的人参考。下面是我必须做的:

const assert = require("chai").assert;
const fetch = require("node-fetch")

const params = new URLSearchParams();

params.append("grant_type", "password");
params.append("username", "JeffUser");
params.append("password", "jeff-password");
params.append("client_id", "jeff-client");
params.append("client_secret", "jeff-client");

describe("Test API", function() {
  let api_token = "";

  it("gets a token", async function() {
    api_token = await fetch("https://some-url/realms/my-realm/protocol/openid-connect/token", {
      method: "post",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      body: params
    }).then (response => {
      return response.json();
    });

    console.log(token);
  });
});

我确保使用body而不是form。我还使用URLSearchParams创建了一系列参数,并将其传递给body参数。这样就成功了!现在我获得了授权令牌。

hmtdttj4

hmtdttj42#

const buffer = require("buffer")
const fetch = require("node-fetch")

let url = 'www.exampl.com/token';
let client_id = '123';
let client_secret = '323';
let username = 'test';
let password = 'test';

let basicAuth = buffer.from(`${client_id}:${client_secret}`).toString("base64");

const response = await fetch(url, {
 method:"POST",
 headers:{ 
    "Content-Type": "application/x-www-form-urlencoded",
    Accept: "application/json; charset=UTF-8", 
     Authorization: `Basic ${basicAuth}`, 
    },
  body:`grant_type=password&username=${username}&password=${password}&scope=xfds`,
});

let token = await response.json();

console.log(token)
1yjd4xko

1yjd4xko3#

    • 使用异步等待**

将其放入Express应用程序请求中,即可开始

const authUrl = "https://accounts.spotify.com/api/token"
const bodyParams = new URLSearchParams()
bodyParams.append("grant_type",'client_credentials')

try{
    let error, response, body = await fetch(authUrl,{
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': 'Basic ' + (Buffer.from(process.env.SPTID + ':' + process.env.SPTSECRET).toString('base64'))
        },
        body: bodyParams
    })
    let response = await data.json()
    let access_token = response.access_token
    console.log(access_token)
    res.sendStatus(200)
}
catch(err){
    console.log(err)
    next(err)
}

相关问题