首页 > 解决方案 > 与 Mojang 身份验证服务器交互的问题

问题描述

我正在尝试从 Mojang 身份验证 API 获取客户端令牌,可以在此处找到https://wiki.vg/Authentication。但是,每当我尝试发出请求时,都会收到以下响应: {error: 'ForbiddenOperationException', errorMessage: 'Forbidden'} API 表明这是因为我的凭据无效,但我收到的 errorMessage 与他们的任何示例都不匹配。我尝试通过 python 的 Requests 模块执行相同的请求,并且效果很好,这让我相信我没有正确发送我的 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();

标签: node.jshttpsminecraft

解决方案


问题是您将凭据直接作为 HTTP 标头而不是作为 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();

推荐阅读