因此,我已阅读以下链接https://github.com/reddit-archive/reddit/wiki/OAuth2上的文档。我正在尝试为我的应用程序检索访问令牌,该令牌只需要Application Only OAuth,因为它不需要用户插入其凭据。我已经按照提到的页面上的说明进行操作,但是我无法检索访问令牌,并且总是得到:
"{\"message\": \"Unauthorized\", \"error\": 401}"
这是我的代码:
#include "reddit.h"
#include <QtNetwork>
#include <QUuid>
const QString GRANT_URL = "https://oauth.reddit.com/grants/installed_client";
const QString ACCESS_TOKEN_URL = "https://www.reddit.com/api/v1/access_token";
const QByteArray CLIENT_IDENTIFIER = "MYID";
Reddit::Reddit(QObject *parent) : QObject(parent)
{
mDeviceID = "DO_NOT_TRACK_THIS_DEVICE";
mAuthHeader = "Basic " + CLIENT_IDENTIFIER.toBase64();
}
void Reddit::getAccessToken()
{
auto netManager = new QNetworkAccessManager(this);
QUrl requestUrl = buildAccessTokenUrl();
QNetworkRequest netRequest(requestUrl);
netRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
netRequest.setRawHeader("Authorization", mAuthHeader);
auto reply = netManager->post(netRequest, requestUrl.query(QUrl::FullyEncoded).toUtf8());
connect(reply, &QNetworkReply::finished, this, &Reddit::accessTokenRequestFinished);
}
void Reddit::accessTokenRequestFinished()
{
auto reply = qobject_cast<QNetworkReply*>(sender());
qDebug() << reply->readAll();
reply->deleteLater();
}
QUrl Reddit::buildAccessTokenUrl()
{
QUrl url(ACCESS_TOKEN_URL);
QUrlQuery urlQuery;
urlQuery.addQueryItem("grant_type", GRANT_URL);
urlQuery.addQueryItem("device_id", mDeviceID);
url.setQuery(urlQuery);
return url;
}
我已使用“已安装”类型选项在https://ssl.reddit.com/prefs/apps/注册了我的应用程序。
答案 0 :(得分:3)
好,所以我发现了问题。我没有阅读'Basic' HTTP Authentication Scheme并忘记了我修改为的授权标头中的:
:
mAuthHeader = "Basic " + (CLIENT_IDENTIFIER + ":").toBase64();