简体   繁体   English

无法使用Reddit API使用Application Only OAuth检索访问令牌

[英]Unable to retrieve access token with Application Only OAuth using Reddit API

So I have read the documentation at the following link https://github.com/reddit-archive/reddit/wiki/OAuth2 . 所以我已经通过以下链接阅读了文档: https://github.com/reddit-archive/reddit/wiki/OAuth2 I am trying to retrieve an access token for my application which only requires an Application Only OAuth since it does not require the user to insert their credentials. 我正在尝试为我的应用程序检索访问令牌,该令牌只需要Application Only OAuth,因为它不需要用户插入其凭据。 I have followed the instructions on the page mentioned, but I am unable to retrieve the access token and I always get: 我已按照上述页面上的说明操作,但我无法检索访问令牌,而且我总是得到:

"{\"message\": \"Unauthorized\", \"error\": 401}"

Here is my code: 这是我的代码:

#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;
}

I have registerd my application at https://ssl.reddit.com/prefs/apps/ using the "installed" type option. 我已使用“已安装”类型选项在https://ssl.reddit.com/prefs/apps/上注册了我的应用程序。

Ok so I found the problem. 好的,我发现了问题。 I didn't read the 'Basic' HTTP Authentication Scheme and forgot a : in my authorization header which I modified to: 我没有阅读'基本'HTTP身份验证方案 ,忘记了:在我修改为的授权标题中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM