Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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.

like image 334
reckless Avatar asked Aug 09 '18 14:08

reckless


1 Answers

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();
like image 61
reckless Avatar answered Oct 19 '22 03:10

reckless