与 Mojang 身份验证服务器交互时出现问题

Problem Interacting With Mojang Authentication Server

我正在尝试从 Mojang 身份验证 API 获取客户端令牌,可在此处找到 https://wiki.vg/Authentication。但是,每当我尝试发出请求时,都会收到以下响应: {error: 'ForbiddenOperationException', errorMessage: 'Forbidden'} API 表示这是因为我的凭据无效但我收到的错误消息与他们的任何示例都不匹配。我尝试通过 python 的请求模块执行相同的请求,并且效果很好,这让我相信我没有正确发送我的 https 请求。我知道我可能忽略了一些非常基本的东西,但如果有人告诉我我做错了什么,我将不胜感激。 这是我的代码:

Python 有效代码:

import requests

url = 'https://authserver.mojang.com/authenticate'
data = {"username":"--username--", "password":"--password--"}
res = requests.post(url, json=data)
print(res.json()) 

Javascript 无效的代码:

var https = require('https');

var options = {
    host: 'authserver.mojang.com',
    path: '/authenticate',
    method: 'POST',
    headers: {"username":"--username--","password":"--password--"}
}

https.request(options, (res)=>{
    var body = ''
    res.on('data', (d)=>{
        body+=d;
    });
    res.on('end', ()=>{
        resp = JSON.parse(body);
        console.log(resp);
    });
}).end();

问题是您将凭据作为 HTTP headers 直接发送,而不是作为 POST 数据发送。试试这个:

var https = require('https');

var data = JSON.stringify({"username":"--username--","password":"--password--"})

var options = {
    host: 'authserver.mojang.com',
    path: '/authenticate',
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': data.length
    }
}

var req = https.request(options, (res)=>{
    var body = ''
    res.on('data', (d)=>{
        body+=d;
    });
    res.on('end', ()=>{
        resp = JSON.parse(body);
        console.log(resp);
    });
});
req.write(data);
req.end();