summaryrefslogtreecommitdiffstats
path: root/src/oauth/qoauth1.cpp
blob: e9def6842d46bd4be9017ef6279a4d3f0c88b7a9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
// Copyright (C) 2017 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only

#include <QtNetwork/qtnetwork-config.h>

#ifndef QT_NO_HTTP

#include "qoauth1.h"
#include "qoauth1_p.h"
#include "qoauth1signature.h"
#include "qoauthoobreplyhandler.h"
#include "qoauthhttpserverreplyhandler.h"

#include <QtCore/qmap.h>
#include <QtCore/qlist.h>
#include <QtCore/qvariant.h>
#include <QtCore/qurlquery.h>
#include <QtCore/qdatetime.h>
#include <QtCore/qbytearray.h>
#include <QtCore/qmessageauthenticationcode.h>

#include <QtNetwork/qnetworkreply.h>
#include <QtNetwork/qnetworkrequest.h>
#include <QtNetwork/qnetworkaccessmanager.h>

QT_BEGIN_NAMESPACE

using namespace Qt::StringLiterals;

/*!
    \class QOAuth1
    \inmodule QtNetworkAuth
    \ingroup oauth
    \brief The QOAuth1 class provides an implementation of the
    \l {https://tools.ietf.org/html/rfc5849}{OAuth 1 Protocol}.
    \since 5.8

    QOAuth1 provides a method for clients to access server resources
    on behalf of a resource owner (such as a different client or an
    end-user). It also provides a process for end-users to authorize
    third-party access to their server resources without sharing
    their credentials (typically, a username and password pair),
    using user-agent redirections.

    QOAuth1 uses tokens to represent the authorization granted to the
    client by the resource owner.  Typically, token credentials are
    issued by the server at the resource owner's request, after
    authenticating the resource owner's identity (usually using a
    username and password).

    When making the temporary credentials request, the client
    authenticates using only the client credentials. When making the
    token request, the client authenticates using the client
    credentials as well as the temporary credentials. Once the
    client receives and stores the token credentials, it can
    proceed to access protected resources on behalf of the resource
    owner by making authenticated requests using the client
    credentials together with the token credentials received.
*/

/*!
    \enum QOAuth1::SignatureMethod

    Indicates the signature method to be used to sign requests.

    \value Hmac_Sha1
    \l {https://tools.ietf.org/html/rfc5849#section-3.4.2}
    {HMAC-SHA1} signature method.

    \value Rsa_Sha1
    \l {https://tools.ietf.org/html/rfc5849#section-3.4.3}
    {RSA-SHA1} signature method (not supported).

    \value PlainText
    \l {https://tools.ietf.org/html/rfc5849#section-3.4.4}
    {PLAINTEXT} signature method.
*/

using OAuth1 = QOAuth1Private::OAuth1KeyString;
const QString OAuth1::oauthCallback =           u"oauth_callback"_s;
const QString OAuth1::oauthCallbackConfirmed =  u"oauth_callback_confirmed"_s;
const QString OAuth1::oauthConsumerKey =        u"oauth_consumer_key"_s;
const QString OAuth1::oauthNonce =              u"oauth_nonce"_s;
const QString OAuth1::oauthSignature =          u"oauth_signature"_s;
const QString OAuth1::oauthSignatureMethod =    u"oauth_signature_method"_s;
const QString OAuth1::oauthTimestamp =          u"oauth_timestamp"_s;
const QString OAuth1::oauthToken =              u"oauth_token"_s;
const QString OAuth1::oauthTokenSecret =        u"oauth_token_secret"_s;
const QString OAuth1::oauthVerifier =           u"oauth_verifier"_s;
const QString OAuth1::oauthVersion =            u"oauth_version"_s;

QOAuth1Private::QOAuth1Private(const QPair<QString, QString> &clientCredentials,
                               QNetworkAccessManager *networkAccessManager) :
    QAbstractOAuthPrivate("qt.networkauth.oauth1",
                          QUrl(),
                          clientCredentials.first,
                          networkAccessManager),
    clientIdentifierSharedKey(clientCredentials.second)
{
    qRegisterMetaType<QNetworkReply::NetworkError>("QNetworkReply::NetworkError");
    qRegisterMetaType<QOAuth1::SignatureMethod>("QOAuth1::SignatureMethod");
}

void QOAuth1Private::appendCommonHeaders(QVariantMap *headers)
{
    const auto currentDateTime = QDateTime::currentDateTimeUtc();

    headers->insert(OAuth1::oauthNonce, QOAuth1::nonce());
    headers->insert(OAuth1::oauthConsumerKey, clientIdentifier);
    headers->insert(OAuth1::oauthTimestamp, QString::number(currentDateTime.toSecsSinceEpoch()));
    headers->insert(OAuth1::oauthVersion, oauthVersion);
    headers->insert(OAuth1::oauthSignatureMethod, signatureMethodString().toUtf8());
}

void QOAuth1Private::appendSignature(QAbstractOAuth::Stage stage,
                                     QVariantMap *headers,
                                     const QUrl &url,
                                     QNetworkAccessManager::Operation operation,
                                     const QMultiMap<QString, QVariant> parameters)
{
    QByteArray signature;
    {
        QMultiMap<QString, QVariant> allParameters(*headers);
        allParameters.unite(parameters);
        if (modifyParametersFunction)
            modifyParametersFunction(stage, &allParameters);
        signature = generateSignature(allParameters, url, operation);
    }
    headers->insert(OAuth1::oauthSignature, signature);
}

QNetworkReply *QOAuth1Private::requestToken(QNetworkAccessManager::Operation operation,
                                            const QUrl &url,
                                            const QPair<QString, QString> &token,
                                            const QVariantMap &parameters)
{
    if (Q_UNLIKELY(!networkAccessManager())) {
        qCWarning(loggingCategory, "QNetworkAccessManager not available");
        return nullptr;
    }
    if (Q_UNLIKELY(url.isEmpty())) {
        qCWarning(loggingCategory, "Request Url not set");
        return nullptr;
    }
    if (Q_UNLIKELY(operation != QNetworkAccessManager::GetOperation &&
                   operation != QNetworkAccessManager::PostOperation)) {
        qCWarning(loggingCategory, "Operation not supported");
        return nullptr;
    }

    QNetworkRequest request(url);

    QAbstractOAuth::Stage stage = QAbstractOAuth::Stage::RequestingTemporaryCredentials;
    QVariantMap headers;
    QMultiMap<QString, QVariant> remainingParameters;
    appendCommonHeaders(&headers);
    for (auto it = parameters.begin(), end = parameters.end(); it != end; ++it) {
        const auto key = it.key();
        const auto value = it.value();
        if (key.startsWith(QStringLiteral("oauth_")))
            headers.insert(key, value);
        else
            remainingParameters.insert(key, value);
    }
    if (!token.first.isEmpty()) {
        headers.insert(OAuth1::oauthToken, token.first);
        stage = QAbstractOAuth::Stage::RequestingAccessToken;
    }
    appendSignature(stage, &headers, url, operation, remainingParameters);

    request.setRawHeader("Authorization", QOAuth1::generateAuthorizationHeader(headers));

    QNetworkReply *reply = nullptr;
    if (operation == QNetworkAccessManager::GetOperation) {
        if (parameters.size() > 0) {
            QUrl url = request.url();
            url.setQuery(QOAuth1Private::createQuery(remainingParameters));
            request.setUrl(url);
        }
        reply = networkAccessManager()->get(request);
    }
    else if (operation == QNetworkAccessManager::PostOperation) {
        QUrlQuery query = QOAuth1Private::createQuery(remainingParameters);
        const QByteArray data = query.toString(QUrl::FullyEncoded).toUtf8();
        request.setHeader(QNetworkRequest::ContentTypeHeader,
                          QStringLiteral("application/x-www-form-urlencoded"));
        reply = networkAccessManager()->post(request, data);
    }

    connect(reply, &QNetworkReply::errorOccurred,
            this, &QOAuth1Private::_q_onTokenRequestError);

    QAbstractOAuthReplyHandler *handler = replyHandler ? replyHandler.data()
                                                       : defaultReplyHandler.data();
    QObject::connect(reply, &QNetworkReply::finished, handler,
                     [handler, reply]() { handler->networkReplyFinished(reply); });
    connect(handler, &QAbstractOAuthReplyHandler::tokensReceived, this,
            &QOAuth1Private::_q_tokensReceived);

    return reply;
}

QString QOAuth1Private::signatureMethodString() const
{
    switch (signatureMethod) { // No default: intended
    case QOAuth1::SignatureMethod::PlainText:
        return QStringLiteral("PLAINTEXT");
    case QOAuth1::SignatureMethod::Hmac_Sha1:
        return QStringLiteral("HMAC-SHA1");
    case QOAuth1::SignatureMethod::Rsa_Sha1:
        qFatal("RSA-SHA1 signature method not supported");
        return QStringLiteral("RSA-SHA1");
    }
    qFatal("Invalid signature method");
    return QString();
}

QByteArray QOAuth1Private::generateSignature(const QMultiMap<QString, QVariant> &parameters,
                                             const QUrl &url,
                                             QNetworkAccessManager::Operation operation) const
{
    QOAuth1Signature signature(url,
                               clientIdentifierSharedKey,
                               tokenSecret,
                               static_cast<QOAuth1Signature::HttpRequestMethod>(operation),
                               parameters);
    return formatSignature(signature);
}

QByteArray QOAuth1Private::generateSignature(const QMultiMap<QString, QVariant> &parameters,
                                             const QUrl &url,
                                             const QByteArray &verb) const
{
    QOAuth1Signature signature(url,
                               clientIdentifierSharedKey,
                               tokenSecret,
                               QOAuth1Signature::HttpRequestMethod::Custom,
                               parameters);
    signature.setCustomMethodString(verb);
    return formatSignature(signature);
}

QByteArray QOAuth1Private::formatSignature(const QOAuth1Signature &signature) const
{
    switch (signatureMethod) {
    case QOAuth1::SignatureMethod::Hmac_Sha1:
        return signature.hmacSha1().toBase64();
    case QOAuth1::SignatureMethod::PlainText:
        return signature.plainText();
    default:
        qFatal("QOAuth1Private::generateSignature: Signature method not supported");
        return QByteArray();
    }
}

QVariantMap QOAuth1Private::createOAuthBaseParams() const
{
    QVariantMap oauthParams;

    const auto currentDateTime = QDateTime::currentDateTimeUtc();

    oauthParams.insert(OAuth1::oauthConsumerKey, clientIdentifier);
    oauthParams.insert(OAuth1::oauthVersion, QStringLiteral("1.0"));
    oauthParams.insert(OAuth1::oauthToken, token);
    oauthParams.insert(OAuth1::oauthSignatureMethod, signatureMethodString());
    oauthParams.insert(OAuth1::oauthNonce, QOAuth1::nonce());
    oauthParams.insert(OAuth1::oauthTimestamp, QString::number(currentDateTime.toSecsSinceEpoch()));

    return oauthParams;
}

/*!
    \reimp
*/
void QOAuth1::prepareRequest(QNetworkRequest *request, const QByteArray &verb,
                                 const QByteArray &body)
{
    QVariantMap signingParams;
    if (verb == "POST" &&
        request->header(QNetworkRequest::ContentTypeHeader).toByteArray()
            == "application/x-www-form-urlencoded") {
        QUrlQuery query(QString::fromUtf8(body));
        for (const auto &item : query.queryItems(QUrl::FullyDecoded))
            signingParams.insert(item.first, item.second);
    }
    setup(request, signingParams, verb);
}

void QOAuth1Private::_q_onTokenRequestError(QNetworkReply::NetworkError error)
{
    Q_Q(QOAuth1);
    Q_UNUSED(error);
    Q_EMIT q->requestFailed(QAbstractOAuth::Error::NetworkError);
}

void QOAuth1Private::_q_tokensReceived(const QVariantMap &tokens)
{
    Q_Q(QOAuth1);

    if (!tokenRequested && status == QAbstractOAuth::Status::TemporaryCredentialsReceived) {
        // We didn't request a token yet, but in the "TemporaryCredentialsReceived" state _any_
        // new tokens received will count as a successful authentication and we move to the
        // 'Granted' state. To avoid this, 'status' will be temporarily set to 'NotAuthenticated'.
        status = QAbstractOAuth::Status::NotAuthenticated;
    }
    if (tokenRequested) // 'Reset' tokenRequested now that we've gotten new tokens
        tokenRequested = false;

    QPair<QString, QString> credential(tokens.value(OAuth1::oauthToken).toString(),
                                       tokens.value(OAuth1::oauthTokenSecret).toString());
    switch (status) {
    case QAbstractOAuth::Status::NotAuthenticated:
        if (tokens.value(OAuth1::oauthCallbackConfirmed, true).toBool()) {
            q->setTokenCredentials(credential);
            setStatus(QAbstractOAuth::Status::TemporaryCredentialsReceived);
        } else {
            Q_EMIT q->requestFailed(QAbstractOAuth::Error::OAuthCallbackNotVerified);
        }
        break;
    case QAbstractOAuth::Status::TemporaryCredentialsReceived:
        q->setTokenCredentials(credential);
        setStatus(QAbstractOAuth::Status::Granted);
        break;
    case QAbstractOAuth::Status::Granted:
    case QAbstractOAuth::Status::RefreshingToken:
        break;
    }
}

/*!
    Constructs a QOAuth1 object with parent object \a parent.
*/
QOAuth1::QOAuth1(QObject *parent) :
    QOAuth1(nullptr,
            parent)
{}

/*!
    Constructs a QOAuth1 object with parent object \a parent, using
    \a manager to access the network.
*/
QOAuth1::QOAuth1(QNetworkAccessManager *manager, QObject *parent) :
    QOAuth1(QString(),
            QString(),
            manager,
            parent)
{}

/*!
    Constructs a QOAuth1 object with parent object \a parent, using
    \a manager to access the network.
    Also sets \a clientIdentifier and \a clientSharedSecret to sign
    the calls to the web server and identify the application.
*/
QOAuth1::QOAuth1(const QString &clientIdentifier,
                 const QString &clientSharedSecret,
                 QNetworkAccessManager *manager,
                 QObject *parent)
    : QAbstractOAuth(*new QOAuth1Private(qMakePair(clientIdentifier, clientSharedSecret),
                                         manager),
                     parent)
{}

/*!
    Returns the current shared secret used to sign requests to
    the web server.

    \sa setClientSharedSecret(), clientCredentials()
*/
QString QOAuth1::clientSharedSecret() const
{
    Q_D(const QOAuth1);
    return d->clientIdentifierSharedKey;
}

/*!
    Sets \a clientSharedSecret as the string used to sign the
    requests to the web server.

    \sa clientSharedSecret(), setClientCredentials()
*/
void QOAuth1::setClientSharedSecret(const QString &clientSharedSecret)
{
    Q_D(QOAuth1);
    if (d->clientIdentifierSharedKey != clientSharedSecret) {
        d->clientIdentifierSharedKey = clientSharedSecret;
        Q_EMIT clientSharedSecretChanged(clientSharedSecret);
    }
}

/*!
    Returns the pair of QString used to identify the application and
    sign requests to the web server.

    \sa setClientCredentials()
*/
QPair<QString, QString> QOAuth1::clientCredentials() const
{
    Q_D(const QOAuth1);
    return qMakePair(d->clientIdentifier, d->clientIdentifierSharedKey);
}

/*!
    Sets \a clientCredentials as the pair of QString used to identify
    the application and sign requests to the web server.

    \sa clientCredentials()
*/
void QOAuth1::setClientCredentials(const QPair<QString, QString> &clientCredentials)
{
    setClientCredentials(clientCredentials.first, clientCredentials.second);
}

/*!
    Sets \a clientIdentifier and \a clientSharedSecret as the pair of
    QString used to identify the application and sign requests to the
    web server. \a clientIdentifier identifies the application and
    \a clientSharedSecret is used to sign requests.

    \sa clientCredentials()
*/
void QOAuth1::setClientCredentials(const QString &clientIdentifier,
                                   const QString &clientSharedSecret)
{
    setClientIdentifier(clientIdentifier);
    setClientSharedSecret(clientSharedSecret);
}

/*!
    Returns the current token secret used to sign authenticated
    requests to the web server.

    \sa setTokenSecret(), tokenCredentials()
*/
QString QOAuth1::tokenSecret() const
{
    Q_D(const QOAuth1);
    return d->tokenSecret;
}
/*!
    Sets \a tokenSecret as the current token secret used to sign
    authenticated calls to the web server.

    \sa tokenSecret(), setTokenCredentials()
*/
void QOAuth1::setTokenSecret(const QString &tokenSecret)
{
    Q_D(QOAuth1);
    if (d->tokenSecret != tokenSecret) {
        d->tokenSecret = tokenSecret;
        Q_EMIT tokenSecretChanged(tokenSecret);
    }
}

/*!
    Returns the pair of QString used to identify and sign
    authenticated requests to the web server.

    \sa setTokenCredentials()
*/
QPair<QString, QString> QOAuth1::tokenCredentials() const
{
    Q_D(const QOAuth1);
    return qMakePair(d->token, d->tokenSecret);
}

/*!
    Sets \a tokenCredentials as the pair of QString used to identify
    and sign authenticated requests to the web server.

    \sa tokenCredentials()
*/
void QOAuth1::setTokenCredentials(const QPair<QString, QString> &tokenCredentials)
{
    setTokenCredentials(tokenCredentials.first, tokenCredentials.second);
}

/*!
    Sets \a token and \a tokenSecret as the pair of QString used to
    identify and sign authenticated requests to the web server.
    Once the client receives and stores the token credentials, it can
    proceed to access protected resources on behalf of the resource
    owner by making authenticated requests using the client
    credentials together with the token credentials received.

    \sa tokenCredentials()
*/
void QOAuth1::setTokenCredentials(const QString &token, const QString &tokenSecret)
{
    setToken(token);
    setTokenSecret(tokenSecret);
}

/*!
    Returns the url used to request temporary credentials to
    start the authentication process.

    \sa setTemporaryCredentialsUrl()
*/
QUrl QOAuth1::temporaryCredentialsUrl() const
{
    Q_D(const QOAuth1);
    return d->temporaryCredentialsUrl;
}

/*!
    Sets \a url as the URL to request temporary credentials to
    start the authentication process.

    \sa temporaryCredentialsUrl()
*/
void QOAuth1::setTemporaryCredentialsUrl(const QUrl &url)
{
    Q_D(QOAuth1);
    if (d->temporaryCredentialsUrl != url) {
        d->temporaryCredentialsUrl = url;
        Q_EMIT temporaryCredentialsUrlChanged(url);
    }
}

/*!
    Returns the url used to request token credentials to continue
    the authentication process.

    \sa setTokenCredentialsUrl()
*/
QUrl QOAuth1::tokenCredentialsUrl() const
{
    Q_D(const QOAuth1);
    return d->tokenCredentialsUrl;
}

/*!
    Sets \a url as the URL to request the token credentials to
    continue the authentication process.

    \sa tokenCredentialsUrl()
*/
void QOAuth1::setTokenCredentialsUrl(const QUrl &url)
{
    Q_D(QOAuth1);
    if (d->tokenCredentialsUrl != url) {
        d->tokenCredentialsUrl = url;
        Q_EMIT tokenCredentialsUrlChanged(url);
    }
}

/*!
    Returns the method used to sign the request to the web server.

    \sa setSignatureMethod()
*/
QOAuth1::SignatureMethod QOAuth1::signatureMethod() const
{
    Q_D(const QOAuth1);
    return d->signatureMethod;
}

/*!
    Sets \a value as the method used to sign requests to the web
    server.

    \sa signatureMethod()
*/
void QOAuth1::setSignatureMethod(QOAuth1::SignatureMethod value)
{
    Q_D(QOAuth1);
    if (d->signatureMethod != value) {
        d->signatureMethod = value;
        Q_EMIT signatureMethodChanged(value);
    }
}

/*!
    Sends an authenticated HEAD request and returns a new
    QNetworkReply. The \a url and \a parameters are used to create
    the request.

    \b {See also}: \l {https://tools.ietf.org/html/rfc2616#section-9.4}
    {Hypertext Transfer Protocol -- HTTP/1.1: HEAD}
*/
QNetworkReply *QOAuth1::head(const QUrl &url, const QVariantMap &parameters)
{
    Q_D(QOAuth1);
    if (!d->networkAccessManager()) {
        qCWarning(d->loggingCategory, "QNetworkAccessManager not available");
        return nullptr;
    }
    QNetworkRequest request(url);
    setup(&request, parameters, QNetworkAccessManager::HeadOperation);
    return d->networkAccessManager()->head(request);
}

/*!
    Sends an authenticated GET request and returns a new
    QNetworkReply. The \a url and \a parameters are used to create
    the request.

    \b {See also}: \l {https://tools.ietf.org/html/rfc2616#section-9.3}
    {Hypertext Transfer Protocol -- HTTP/1.1: GET}
*/
QNetworkReply *QOAuth1::get(const QUrl &url, const QVariantMap &parameters)
{
    Q_D(QOAuth1);
    if (!d->networkAccessManager()) {
        qCWarning(d->loggingCategory, "QNetworkAccessManager not available");
        return nullptr;
    }
    QNetworkRequest request(url);
    setup(&request, parameters, QNetworkAccessManager::GetOperation);
    QNetworkReply *reply = d->networkAccessManager()->get(request);
    connect(reply, &QNetworkReply::finished, this, [this, reply]() { emit finished(reply); });
    return reply;
}

/*!
    Sends an authenticated POST request and returns a new
    QNetworkReply. The \a url and \a parameters are used to create
    the request.

    \b {See also}: \l {https://tools.ietf.org/html/rfc2616#section-9.5}
    {Hypertext Transfer Protocol -- HTTP/1.1: POST}
*/
QNetworkReply *QOAuth1::post(const QUrl &url, const QVariantMap &parameters)
{
    Q_D(QOAuth1);
    if (!d->networkAccessManager()) {
        qCWarning(d->loggingCategory, "QNetworkAccessManager not available");
        return nullptr;
    }
    QNetworkRequest request(url);
    setup(&request, parameters, QNetworkAccessManager::PostOperation);
    d->addContentTypeHeaders(&request);

    const QByteArray data = d->convertParameters(parameters);
    QNetworkReply *reply = d->networkAccessManager()->post(request, data);
    connect(reply, &QNetworkReply::finished, this, [this, reply]() { emit finished(reply); });
    return reply;
}

/*!
    Sends an authenticated PUT request and returns a new
    QNetworkReply. The \a url and \a parameters are used to create
    the request.

    \b {See also}: \l {https://tools.ietf.org/html/rfc2616#section-9.6}
    {Hypertext Transfer Protocol -- HTTP/1.1: PUT}
*/
QNetworkReply *QOAuth1::put(const QUrl &url, const QVariantMap &parameters)
{
    Q_D(QOAuth1);
    if (!d->networkAccessManager()) {
        qCWarning(d->loggingCategory, "QNetworkAccessManager not available");
        return nullptr;
    }
    QNetworkRequest request(url);
    setup(&request, parameters, QNetworkAccessManager::PutOperation);
    d->addContentTypeHeaders(&request);

    const QByteArray data = d->convertParameters(parameters);
    QNetworkReply *reply = d->networkAccessManager()->put(request, data);
    connect(reply, &QNetworkReply::finished, this, std::bind(&QAbstractOAuth::finished, this, reply));
    return reply;
}

/*!
    Sends an authenticated DELETE request and returns a new
    QNetworkReply. The \a url and \a parameters are used to create
    the request.

    \b {See also}: \l {https://tools.ietf.org/html/rfc2616#section-9.7}
    {Hypertext Transfer Protocol -- HTTP/1.1: DELETE}
*/
QNetworkReply *QOAuth1::deleteResource(const QUrl &url, const QVariantMap &parameters)
{
    Q_D(QOAuth1);
    if (!d->networkAccessManager()) {
        qCWarning(d->loggingCategory, "QNetworkAccessManager not available");
        return nullptr;
    }
    QNetworkRequest request(url);
    setup(&request, parameters, QNetworkAccessManager::DeleteOperation);
    QNetworkReply *reply = d->networkAccessManager()->deleteResource(request);
    connect(reply, &QNetworkReply::finished, this, [this, reply]() { emit finished(reply); });
    return reply;
}

/*!
    Starts the a request for temporary credentials using the request
    method \a operation. The request URL is \a url and the
    \a parameters shall encoded and sent during the request.

    \b {See also}: \l {https://tools.ietf.org/html/rfc5849#section-2.1}
    {The OAuth 1.0 Protocol: Temporary Credentials}
*/
QNetworkReply *QOAuth1::requestTemporaryCredentials(QNetworkAccessManager::Operation operation,
                                                    const QUrl &url,
                                                    const QVariantMap &parameters)
{
    Q_D(QOAuth1);
    d->token.clear();
    d->tokenSecret.clear();
    QVariantMap allParameters(parameters);
    allParameters.insert(OAuth1::oauthCallback, callback());
    return d->requestToken(operation, url, qMakePair(d->token, d->tokenSecret), allParameters);
}

/*!
    Starts a request for token credentials using the request
    method \a operation. The request URL is \a url and the
    \a parameters shall be encoded and sent during the
    request. The \a temporaryToken pair of string is used to identify
    and sign the request.

    \b {See also}: \l {https://tools.ietf.org/html/rfc5849#section-2.3}
    {The OAuth 1.0 Protocol: Token Credentials}
*/
QNetworkReply *QOAuth1::requestTokenCredentials(QNetworkAccessManager::Operation operation,
                                                const QUrl &url,
                                                const QPair<QString, QString> &temporaryToken,
                                                const QVariantMap &parameters)
{
    Q_D(QOAuth1);
    d->tokenRequested = true;
    return d->requestToken(operation, url, temporaryToken, parameters);
}

/*!
    Signs the \a request using \a signingParameters and \a operation.

    \overload
*/
void QOAuth1::setup(QNetworkRequest *request,
                    const QVariantMap &signingParameters,
                    QNetworkAccessManager::Operation operation)
{
    Q_D(const QOAuth1);

    auto oauthParams = d->createOAuthBaseParams();

    // Add signature parameter
    {
        QMultiMap<QString, QVariant> parameters(oauthParams);
        parameters.unite(QMultiMap<QString, QVariant>(signingParameters));
        const auto signature = d->generateSignature(parameters, request->url(), operation);
        oauthParams.insert(OAuth1::oauthSignature, signature);
    }

    if (operation == QNetworkAccessManager::GetOperation) {
        if (signingParameters.size()) {
            QUrl url = request->url();
            QUrlQuery query = QUrlQuery(url.query());
            for (auto it = signingParameters.begin(), end = signingParameters.end(); it != end;
                 ++it)
                query.addQueryItem(it.key(), it.value().toString());
            url.setQuery(query);
            request->setUrl(url);
        }
    }

    request->setRawHeader("Authorization", generateAuthorizationHeader(oauthParams));

    if (operation == QNetworkAccessManager::PostOperation
            || operation == QNetworkAccessManager::PutOperation)
        request->setHeader(QNetworkRequest::ContentTypeHeader,
                           QStringLiteral("application/x-www-form-urlencoded"));
}

/*!
    \since 5.13

    Signs the \a request using \a signingParameters and \a operationVerb.

    \overload
*/
void QOAuth1::setup(QNetworkRequest *request, const QVariantMap &signingParameters, const QByteArray &operationVerb)
{
    Q_D(const QOAuth1);

    auto oauthParams = d->createOAuthBaseParams();

    // Add signature parameter
    {
        QMultiMap<QString, QVariant> parameters(oauthParams);
        parameters.unite(QMultiMap<QString, QVariant>(signingParameters));
        const auto signature = d->generateSignature(parameters, request->url(), operationVerb);
        oauthParams.insert(OAuth1::oauthSignature, signature);
    }

    request->setRawHeader("Authorization", generateAuthorizationHeader(oauthParams));
}

/*!
    Generates a nonce.

    \b {See also}: \l {https://tools.ietf.org/html/rfc5849#section-3.3}
    {The OAuth 1.0 Protocol: Nonce and Timestamp}
*/
QByteArray QOAuth1::nonce()
{
    return QAbstractOAuth::generateRandomString(8);
}

/*!
    Generates an authorization header using \a oauthParams.

    \b {See also}: \l {https://tools.ietf.org/html/rfc5849#section-3.5.1}
    {The OAuth 1.0 Protocol: Authorization Header}
*/
QByteArray QOAuth1::generateAuthorizationHeader(const QVariantMap &oauthParams)
{
    // TODO Add realm parameter support
    bool first = true;
    QString ret(QStringLiteral("OAuth "));
    QVariantMap headers(oauthParams);
    for (auto it = headers.begin(), end = headers.end(); it != end; ++it) {
        if (first)
            first = false;
        else
            ret += QLatin1String(",");
        ret += it.key() +
               QLatin1String("=\"") +
               QString::fromUtf8(QUrl::toPercentEncoding(it.value().toString())) +
               QLatin1Char('\"');
    }
    return ret.toUtf8();
}

/*!
    Starts the Redirection-Based Authorization flow.

    \note For an out-of-band reply handler, a verifier string is
    received after the call to this function; pass that to
    continueGrantWithVerifier() to continue the grant process.

    \sa continueGrantWithVerifier()

    \b {See also}: \l {https://tools.ietf.org/html/rfc5849#section-2}
    {The OAuth 1.0 Protocol: Redirection-Based Authorization}
*/
void QOAuth1::grant()
{
    Q_D(QOAuth1);
    if (d->temporaryCredentialsUrl.isEmpty()) {
        qCWarning(d->loggingCategory, "requestTokenUrl is empty");
        return;
    }
    if (d->tokenCredentialsUrl.isEmpty()) {
        qCWarning(d->loggingCategory, "authorizationGrantUrl is empty");
        return;
    }
    if (!d->token.isEmpty() && status() == Status::Granted) {
        qCWarning(d->loggingCategory, "Already authenticated");
        return;
    }

    QMetaObject::Connection connection;
    connection = connect(this, &QAbstractOAuth::statusChanged, this, [&](Status status) {
        Q_D(QOAuth1);

        if (status == Status::TemporaryCredentialsReceived) {
            if (d->authorizationUrl.isEmpty()) {
                // try upgrading token without verifier
                auto reply = requestTokenCredentials(QNetworkAccessManager::PostOperation,
                                                     d->tokenCredentialsUrl,
                                                     qMakePair(d->token, d->tokenSecret));
                connect(reply, &QNetworkReply::finished, reply, &QNetworkReply::deleteLater);
            } else {
                QMultiMap<QString, QVariant> parameters;
                parameters.insert(OAuth1::oauthToken, d->token);
                if (d->modifyParametersFunction)
                    d->modifyParametersFunction(Stage::RequestingAuthorization, &parameters);

                // https://tools.ietf.org/html/rfc5849#section-2.2
                resourceOwnerAuthorization(d->authorizationUrl, parameters);
            }
        } else if (status == Status::NotAuthenticated) {
            // Inherit class called QAbstractOAuth::setStatus(Status::NotAuthenticated);
            setTokenCredentials(QString(), QString());
            disconnect(connection);
        }
    });

    auto httpReplyHandler = qobject_cast<QOAuthHttpServerReplyHandler*>(replyHandler());
    if (httpReplyHandler) {
        auto func = [this](const QVariantMap &values) {
            Q_D(QOAuth1);
            QString verifier = values.value(OAuth1::oauthVerifier).toString();
            if (verifier.isEmpty()) {
                qCWarning(d->loggingCategory, "%s not found in the callback",
                          qPrintable(OAuth1::oauthVerifier));
                return;
            }
            continueGrantWithVerifier(verifier);
        };
        connect(httpReplyHandler, &QOAuthHttpServerReplyHandler::callbackReceived, this, func);
    }

    // requesting temporary credentials
    auto reply = requestTemporaryCredentials(QNetworkAccessManager::PostOperation,
                                             d->temporaryCredentialsUrl);
    connect(reply, &QNetworkReply::finished, reply, &QNetworkReply::deleteLater);
}

/*!
    Continues the Redirection-Based Authorization flow using
    \a verifier. Call this function when using an Out-of-band reply
    handler to supply the verifier provided by the web server.
*/
void QOAuth1::continueGrantWithVerifier(const QString &verifier)
{
    // https://tools.ietf.org/html/rfc5849#section-2.3
    Q_D(QOAuth1);

    QVariantMap parameters;
    parameters.insert(OAuth1::oauthVerifier, verifier);
    auto reply = requestTokenCredentials(QNetworkAccessManager::PostOperation,
                                         d->tokenCredentialsUrl,
                                         qMakePair(d->token, d->tokenSecret),
                                         parameters);
    connect(reply, &QNetworkReply::finished, reply, &QNetworkReply::deleteLater);
}

QT_END_NAMESPACE

#endif // QT_NO_HTTP