【问题标题】:Unable to retrieve access token with Application Only OAuth using Reddit API无法使用 Reddit API 通过仅应用程序 OAuth 检索访问令牌
【发布时间】:2019-01-17 02:15:36
【问题描述】:

所以我已经阅读了以下链接https://github.com/reddit-archive/reddit/wiki/OAuth2 上的文档。我正在尝试为我的应用程序检索访问令牌,该令牌仅需要仅应用程序 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/ 注册了我的应用程序。

【问题讨论】:

  • 不是您的问题的解决方案,但 Qt 已经有一个用于 OAUTH 的库!其中一个例子是 reddit API。查看doc.qt.io/qt-5.11/qtnetworkauth-index.html
  • 嗯,是的,我已经看过它并尝试使用该库实现,但是我发现文档有点混乱。我不明白是否以及如何实现“仅应用程序”OAuth,因为示例仅演示了基于用户的 OAuth

标签: c++ qt rest oauth-2.0 reddit


【解决方案1】:

好的,我发现了问题。我没有阅读'Basic' HTTP Authentication Scheme 并在我修改为的授权标头中忘记了:

mAuthHeader = "Basic " + (CLIENT_IDENTIFIER + ":").toBase64();

【讨论】:

    猜你喜欢
    • 2021-06-20
    • 2013-02-23
    • 2021-01-10
    • 2015-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-21
    • 1970-01-01
    相关资源
    最近更新 更多