5

So I have read the documentation at the following link 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. 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.

reckless
  • 741
  • 12
  • 53
  • Not a solution for for your problem, but Qt already has a library for OAUTH! And one of the examples is for the reddit API. Check out https://doc.qt.io/qt-5.11/qtnetworkauth-index.html – Felix Aug 11 '18 at 12:43
  • Hmm yeah I have looked at it and tried implement with that library, however I found the documentation to be a bit confusing. I didn't understand if and how was possible to implement an "Application only" OAuth as the examples only demonstrate a user based OAuth – reckless Aug 11 '18 at 13:25

1 Answers1

4

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:

mAuthHeader = "Basic " + (CLIENT_IDENTIFIER + ":").toBase64();
Community
  • 1
  • 1
reckless
  • 741
  • 12
  • 53