Comments, Code and Qt. Some words about the wonderful world of software engineering


Introducing kQOAuth – Easy and Powerful OAuth library for Qt

kQOAuth is a powerful yet easy way to integrate OAuth authentication to your Qt application. kQOAuth handles OAuth request signing, request submitting and reply parsing for you. It also provides an easy way to retrieve user authorization to protected resources with a built in HTTP server. All this is done with Qt programming in mind, so you can use Qt's signals to react to OAuth events in your own application. This also means that the library works fully asynchronously. kQOAuth is licensed under the LGPL license. You can read more about kQOAuth usage in my next post: Advanced use of kQOAuth. There is now also an official web page for kQOAuth: If you are unfamiliar with OAuth, it is worth first checking out some tutorials:


kQOAuth is written in C++ and its main features include:
  • Provides easy, "automated", OAuth authentication but also more advanced detailed control of the authentication process.
  • OAuth request handling (request signing, submitting and result parsing).
  • No dependencies to external libraries, for example QCA.
  • Works with signals and slots - asynchronously.
  • Handles protected resource owner authentication by taking care of opening temporary token retrieval web page and parsing the reply with a built in HTTP server.

Download and source code

kQOAuth library source code is available on at

Usage - the easy way

kQOAuth can be used in two different ways. If you don't want to control the authentication process in detail, you can use the convenience APIs to get access to protected resources with a few lines of code.The only pieces of information you will need are
  • your application's consumer key
  • your application's secret consumer key
  • URL for retrieving the temporary request tokens
  • URL for the user to authenticate the application to access the protected resources
  • URL for sending the authenticated request.
All of the above information should be available from the service provider. The example below is taken from the Twitter CLI example application. Please note that parameter names are included in the connect() statements in the examples below for the purpose of clarity. To see the complete compilable example, please check the TwitterCLI example application.

Temporary token.

You will need to start OAuth authentication by creating a KQOAuthRequest and initialize it to be of type KQOAuthRequest::TemporaryCredential. If you want to use the easy, "automated", approach for OAuth authentication then this is probably your hardest step. And even this is not that hard. KQOAuthManager *oauthManager = new KQOAuthManager(this); connect(oauthManager, SIGNAL(temporaryTokenReceived(QString oauthToken, QString oauthTokenSecret)), this, SLOT(onTemporaryTokenReceived(QString oauthToken, QString oauthTokenSecret))); KQOAuthRequest *oauthRequest = new KQOAuthRequest; oauthRequest->initRequest(KQOAuthRequest::TemporaryCredentials, QUrl(temporaryTokenEndpoint)); oauthRequest->setConsumerKey(consumerKey); oauthRequest->setConsumerSecretKey(consumerKeySecret); oauthManager->setHandleUserAuthorization(true); oauthManager->executeRequest(oauthRequest); That's it.Let's see the details. KQOAuthManager *oauthManager = new KQOAuthManager(this); connect(oauthManager, SIGNAL(temporaryTokenReceived(QString oauthToken, QString oauthTokenSecret)), this, SLOT(onTemporaryTokenReceived(QString oauthToken, QString oauthTokenSecret))); Here you first create the KQOAuthManager which will handle the state of the OAuth authentication process. You connect the signal temporaryTokenReceived(QString oauthToken, QString oauthTokenSecret)) to an appropriate slot and as a result you will get the temporary request tokens which you will need in next steps of the authentication process. Actually not even that, but we'll get to that in a short while. KQOAuthRequest *oauthRequest = new KQOAuthRequest; QUrl temporaryTokenEndpoint(""); oauthRequest->initRequest(KQOAuthRequest::TemporaryCredentials, QUrl(temporaryTokenEndpoint)); oauthRequest->setConsumerKey(consumerKey); oauthRequest->setConsumerSecretKey(consumerKeySecret); Next you will create a KQOAuthRequest request that will be sent using the KQOAuthManager. initRequest() call will initialize the request to be a request that will fetch the temporary request tokens and it will also need the service endpoint for retrieving the tokens. You also give the request your consumer key and consumer secret key. These are needed for signing the request and for the service to know who is asking for permissions. oauthManager->setHandleUserAuthorization(true); If you specify this to be true, this will notify the KQOAuthManager that you want it to take care of user authorization on your behalf. What this does is that it will open the user's web browser for authentication and setup a HTTP server that will retrieve the result and parse them for you. To initiate this, just one command is needed in next phase. oauthManager->executeRequest(oauthRequest); The request which was initialized will be signed and sent by the KQOAuthManager to the endpoint. It will also take care of signaling you when the tokens are available. The signal temporaryTokenReceived(QString oauthToken, QString oauthTokenSecret) is emited with the resulting temporary request tokens.

User authorization

We now have the request tokens that we can use to retrieve user's authorization for us to access the protected resources. Below is the Qt slot which was called as a result of the signal. The signal contains the retrieved temporary tokens, but as  you can see from the code below you don't really need them if you want to do the easy OAuth authentication process. The slot below we will ask KQOAuthManager to handle user authorization for us and we connect the signal authorizationReceived(QString oauthToken, QString oauthVerifier) to a slot that is called after this step is concluded. The signal will contain the oauth_verifier token we need in the next step. void TwitterCLI::onTemporaryTokenReceived(QString token, QString tokenSecret) { connect(oauthManager, SIGNAL(authorizationReceived(QString oauthToken, QString oauthVerifier)), this, SLOT( onAuthorizationReceived(QString oauthToken, QString oauthVerifier))); if( oauthManager->lastError() == KQOAuthManager::NoError) { oauthManager->getUserAuthorization(QUrl("")); } } If you did set oauthManager->setHandleUserAuthorization(true) then this is all you need for retrieving the user's authorization to the protected resources (i.e. user will grant your application access to the information you are interested in). The URL given above is the service's URL for providing the user's authorization to protected resources. What the request above will do is:
  • Open the user's web browser to the authorization URL with the correct token.
  • Use an internally generated URL as the callback URL where the service will return after user's authoriszation
  • Setup a HTTP server listening on the generated URL.
  • Parse the reply and provide you with the oauth_verifier token needed in next step (but you will not need this if you don't want to).
authorizationRecieved(oauth_token, oauth_verifier) signal is emitted when the user has authorized the application.

Access tokens

The user has now authorized us to access the protected resources. The last step before we can access the protected resources is to exchange the temporary request tokens (retrieved from the first step) for access tokens which are used when accessing the protected resources. Below is the slot that is called after the user has authorized us to access the protected resources. void TwitterCLI::onAuthorizationReceived(QString token, QString verifier) { connect(oauthManager, SIGNAL(accessTokenReceived(QString oauthToken, QString oauthTokenSecret)), this, SLOT(onAccessTokenReceived(QString oauthToken, QString oauthTokenSecret))); oauthManager->getUserAccessTokens(QUrl("")); } token parameter is our temporary request token which is identifying our authentication session. The verifier parameter is our verifier code which identifies the user's authentication to protected resources. These are sent as the signal parameters from the previous step, but in this easy authentication process you don't need them. Above is the only step you do to in order to exchange the temporary request tokens for the access tokens which we need when sending request to the protected resource. The URL is the service's endpoint for exchanging the tokens. As you can see again, we connect the signal accessTokenReceived(QString oauthToken, QString oauthTokenSecret) to a slot with the resulting tokens from this step.

Sending authenticated requests

We are finally done! When this slot is called, you are authenticated to access the protected resources. The signal parameters provide you with the access tokens, which you want to keep in a secure place. With these tokens you can access the protected resource until the user revokes the tokens. Please note that again following this easy OAuth authentication process you will not need the token parameters - these are taken care of by the manager. Below is the slot which is called when we have access to protected resources. In this slot we can start communicating to the service and do what we actually wanted to do. In this example I am going to send a tweet to Twitter. The tweet will be sent from the account which provided us access to its account. void TwitterCLI::onAccessTokenReceived(QString token, QString tokenSecret) { QUrl requestEndpoint(""); KQOAuthParameters params; params.insert("status", "Hello, World!"); oauthManager->sendAuthorizedRequest(requestEndpoint, requestParameters); } And now the world can see your tweet from your application! When the request is done, the KQOAuthManager will emit the signal authorizedRequestReady() and this will conclude the kQOAuth interactions.

Example application - command line Twitter client

kQOAuth provides as example application a command line tool for sending Twitter updates - tweets. The command line tool uses the easy authentication process to retrieve access tokens and will store them with QSettings. After that you can send tweets from the command line.
twittercli -a          -- This will request for the access tokens and do all the steps between.
twittercli -t 'Hello!' -- This will send the tweet "Hello!" to Twitter.
The Twitter command line example application is available on at


kQOAuth is still at version 0.91. Use it at your own risk. It has so far been tested on Mac OS X 10.6. and Linux (Ubuntu 10.10). Only Qt 4.7 and newer are supported. kQOAuth still supports only HMAC-SHA1 signing method. Patches are welcome.

Technorati Tags: , , , , ,

  • Rob Guthrie

    Hi, I’m really interested in this, and am considering using it for a thing I’m working on.. Particularly because I don’t know that much (yet) about OAuth. My initial investigations on wikipedia come up with this..
    “OAuth 2.0 is the next evolution of the OAuth protocol and is not backward compatible with OAuth 1.0”

    and this..
    “Facebook’s new Graph API only supports OAuth 2.0”

    So It prompts me to ask you.. (as politely as I can, without placing expectation upon yourself) have you considered what will be required to support OAuth2? Do you have plans towards supporting that standard?

    Ok here is something relevant.. I can’t use my gmail account as an open id on your post form. Is that relevant to this standards question?

    • Hi,

      Thanks for bringing up OAuth 2.0. At the time being, I wanted to start by supporting the Twitter use case so I wanted to focus on the 1.0 version. I’ve also understood that 2.0 is not really a standard yet (but I am sure it will be soon).

      But yes, my plans for the future are to continue developing kQOAuth and I will definitely take a look at version 2.0 to include it into kQOAuth. Still too early to say anything about the schedule, though 🙂

      About your OpenID question: Hmm, as I use the service to integrate this commenting system to the blog I need to check with them how GMail accounts are supported.

  • scm

    Does it support QML ? So I can rewrite the qt demo at demos/declarative/twitter/ using your library

    • Hi,

      Well, yes and no.

      You would not be able to put this code directly into a QML file. But since you can execute C++ code (via Q_INVOKABLE properties. Here’s one example: I am sure you can integrate this library to the QML Twitter application. But you would need to modify the QML code (so that it initiates the authentication via a Q_INVOKABLE call) and include a C++ backend that integrates kQOAuth.

      Let me know how it went 🙂

  • Anonymous

    Wow, was just looking for a good Qt OAuth library! Already found QOAuth which seemed also quite nice, but depends on QCA. The lack of support for OAuth 2.0 is a bit of a issue for me, as some of the services I would like to use, only use that. A great post anyway!

    • Thanks for the good feedback! I will improve on the documentation the next few days and will post updates here about that too.

      I can’t promise anything about a schedule, but I am sure OAuth 2.0 is something I want to support too. First I wanted to cover the Twitter use case, hence only 1.0 to start with.

  • Anonymous

    Hey! I’m trying to compile KQOAuth with mingw32-make, and getting this error:

    kqoauthutils.cpp: In static member function ‘static QString KQOAuthUtils::hmac_sha1(const QString&, const QString&)’:
    kqoauthutils.cpp:47: error: ‘bzero’ was not declared in this scope
    kqoauthutils.cpp:50: error: ‘bcopy’ was not declared in this scope
    mingw32-make.EXE[2]: *** [tmp/kqoauthutils.o] Error 1

    Just cloned it from Gitorious repository. What might be wrong?

    • Anonymous

      Nevermind, fixed the bzero and bcopy by adding this to the kqoauthutils.h:

      #define bzero(b,len) (memset((b), ”, (len)), (void) 0)
      #define bcopy(b1,b2,len) (memmove((b2), (b1), (len)), (void) 0)

      But now I’m getting this in the end:

      g++ -enable-stdcall-fixup -Wl,-enable-auto-import -Wl,-enable-runtime-pseudo-reloc -mthreads -Wl -Wl,-subsystem,windows -o debugtwittercli.
      exe debug/twittercli.o debug/moc_twittercli.o -L”c:QtQt4.7.0qtlib” -lmingw32 -lqtmaind -LC:/Users/Alex/kqoauth/lib -lkqoauth -lQtGuid4
      -lQtNetworkd4 -lQtCored4
      c:/qt/qt4.7.0/mingw/bin/../lib/gcc/mingw32/4.4.0/../../../../mingw32/bin/ld.exe: cannot find -lkqoauth
      collect2: ld returned 1 exit status

      Where this -lkqoauth can be found?

      • kqoauth is the library name that is the result when you compile the project. The error indicates that it tries to look for the library called kqoauth in the system default lib locations. This is expected if you haven’t installed kqoauth (with make install – not sure if this works on Windows) and now it can’t find the KQOAuth library in the default locations when linking together the TwitterCLI application.

        I apologize for this, but I haven’t compiled KQOAuth on Windows. But this should be easy to fix; just add to TwitterCLI .pro file to LIBS the location of the path where your kqoauth library is when you compiled it.

        • Anonymous

          Tried running mingw32-make install from kqoauthsrc (after successful creation of kqoauthd0.dll in lib folder). Didn’t helped.

          I got compiled libraries – got kqoauthd0.dll and libkqoauthd0.a files generated in lib folder. Then I tried manually copying them to the qtlib, qtbin places. I’ve added the path to lib folder to kqoauth.prf and No success so far. Still getting this “cannot find -lkqoauth” error.

        • Did you try this to
          win32:LIBS += c:/path/to/lib/dir ?

          Then qmake and make.

          This is an linking issue that the linker just can’t find the library so hope that will solve it.

          More info here:

        • Anonymous

          Btw, how the linker know that -lqkoauth is referring to kqoauthd0.dll?

      • kypeli

        Just wanted to let you know, that I removed those C char pointers and replaced them with pure Qt implementation. This shouldn’t be a problem for anyone else from now on. I should have done this already earlier, but…

    • Oh, btw. I did some time ago already some changes so that this kind of compilation errors are not an issue anymore.

  • Lemonlinger

    Hello, first I want to syay that KQOAuth is a very good Qt OAUTH library.BUT,I have some problems when I use it.
    when I create a request that requst user’s authorization,I do not provide a callback URL.So ,after the Service Provider display the verification code,I must manually inform my application(i.e. copy it to a QTextEdit),and then, I can use it for requesting access token. However, I do not know how to do it.Because I can not find a function which can be called for setting the verification code manually.
    My English is very poor.Hope you can understand me! THANK YOU!!

    • First of all, apologizes for the late reply.Secondly, thank you for your kind words :)Let me try to help you. If I understood you correctly, you get a verification code from the service that the user shall enter manually in your app, and you will use that code to retrieve access token with? If this is the case, you should create a KQOAuthRequest of type “KQOAuthRequest::AccessToken” and set the retrieved verification code with setVerifier(QString) ( for the request that you use to retrieve the access token with.Hope it helps!

      • Lemonlinger

        Thank you very much.It do really helps me! haha~~

  • Hi, this OAuth library looks great, but I have troubles with build QtKOAuth on Archlinux.
    Please, can you tell me correct how-to ?
    When I try ussual make & make install, it’s doesn’t work.
    In /usr/include/QtKOAuth is missing files, file QtKOAuth points to not existing ../src/, etc.
    Thanks for help.

  • Anonymous

    in you example, the signal are not used correctly. the name of the parameters should not be present

    • Yes I know. That is why it says in the text above “Please note that parameter names are included in the connect() statements in the examples below for the purpose of clarity.”

      • Anonymous

        i should really learn to read all the text, and not only copy / paste the code i need ^^

        • That’s ok 🙂 If you need a complete example, please refer to the twittercli application in the examples/ dir.

  • Anonymous

    Another thing : my understanding here is that in the case of twitter, it seems that the twitter application must be configured as “Browser”, with any callback URL (which is overriden anyway) in order to have it working (at least, it seems to be the cas for me, as I could not have the token request work until i configured it this way)

    • The short answer is, yes. The long answer is “if you would like it to be that way”.

      Let me explain. When Twitter says “Browser application”, they really mean any application that can use a callback URL for retrieving the authorisation. So in the case of kQOAuth if you use the built in mechanism to retrieving the user’s authorization, then this is what you want. But as kQOAuth let’s you set any service specific parameters to the requests, you may, if you want to, also use the way of the user providing the access ID numbers to your application that you can send to Twitter.

  • Vdharankar

    can this be used with Qt / QML for Symbian ? I wish to use it to build mobile apps 

    • Hi Vdharankar,

      Since kQOAuth is a C++ library, it can be used as the backend of your QML application. But there is no pure QML implementation available.

      As for Symbian, I know people have used kQOAuth with Symbian. But I don’t have experience with Symbian (nor do I have intents to acquire such without a reasonable amount of money) so I cannot help you with linking kQOAuth in Symbian. You can, however, include kQOAuth to your app’s sources, but that would make your application open source too due to the licensing. 

      • Deionut

        I know LGPL requires open sourcing only if I made changes to kQOAuth; so if I want to use kQOAuth sources directly within my app, for easy integration (so that I do not have to link against libs, etc), but I will not modify in any way kQOAuth sources, do I still need to make my app open source?

        • LGPL lets you only *dynamically* link the library with your application without your application getting the same license as kQOAuth. In all other cases the app will get the same license as kQOAuth.

          Hence, if you compile in the source code of kQOAuth to your app, your application will also become LGPL licensed. 

  • I am having problems making the twittercli work.  I have the 5 item below and have put them into the code but when I run the test with -t “TWEET” I get a error message qDebug() << "No access tokens. Aborting.";.   The -a option seems to work.  What do I need to do to actaully send a tweet?  I am running windows 7.


    your application's consumer key
    your application's secret consumer key
    URL for retrieving the temporary request tokens
    URL for the user to authenticate the application to access the protected resources
    URL for sending the authenticated request.

    • It sounds like the first step (with argument -a) did not work, or for some other reason when sending the tweet, the TwitterCLI example cannot find the access token. Are there any errors visible when running it with -a? Ensure that you run the TwitterCLI with debug output enabled (should be by default). You should also output the replies from the service (Twitter in this case) to see if it replies with some error (sorry, I can’t recall if this is enabled by default in the TwitterCLI example :))

  • Cédric Bonnier

    Hi, I’m working on an application to upload videos on the vimeo website but I’m not really happy with the signal/slot thing of kQOAuth.
    When you want to upload something on, you have to make several calls to their API (see, so with this way of handling requests, I have to disconnect the requestReady signal and reconnect it to the right slot that handles my request. It also have the drawback to split the upload method in as many methods as you need to call (in that case at least 5, more if you want to add a title, comment, etc.). I would have expected to be able to do something like that:

    QMultiMap res = oauthManager.processRequest(request);

    Is there a way to go around this signal/slot thing? Or maybe I missed something, I discovered OAuth 3 days ago and I still don’t feel comfortable with it, even if I read a lot about it. Thanks for your work on kQOAuth, it definitely helped me.

    • Inherently Qt’s network stack is asynchronous and built with signals and slots (as are many other things in Qt as you may know). This is a good thing and I intentionally wanted to keep kQOAuth like this too. To add own threads and mask the functionality to be synchronous (and block the main thread) is like picking blood from the nose. It would over complicate things without a good reason.

      I don’t know your app or the source code you are working on, but if Vimeo’s upload really requires 5 stages, then I would assume you can introduce a state variable in the slot that is called when one request is completed and that way work around the complicated communication to Vimeo. For example. I do not see a reason to make kQOAuth synchronous just because of Vimeo (unless they pay me to do it :)).

      • Cedric

        Yeah I understand your point of view, it makes perfect sense when you want to call a single function of an API. But how do you proceed when you want to call 2 functions and you expect a result from each one?

        For example calling a getUserName and a getUserQuota. You would expect from each one a result that you want to parse. If you call the 2 functions asynchronously, are you 100% sure that you will receive the answer in the same order as you called the functions? If yes then you can store a queue of request and know what to parse when you receive an answer (first a user name, then a user quota).

        Currently, as I’m not sure that the result would arrive in the exact same order as the calls, I’m just waiting for the first answer before doing another API call, which I thinks is weird for single API calls. When you need the result of a method to build the next one is another problem…

        Maybe you would be interested in the code to integrate as a less trivial example? For now I’m still testing the vimeo API and the code is a mess, but when finished I would be happy to share, if it can help others…

        • So if the only issue is to process the result of multiple authorized requests in a single slot, maybe you can use “executeAuthorizedRequest(KQOAuthRequest *request, int id);” method to do the request?

          For that method, you can give your own id (an enum value for example) to distinguish a request from another in the slot. You can do this as the slot “void authorizedRequestReady(QByteArray networkReply, int id);” is called and the same id is returned to you there. In that case you can probably have a switch case to process the results differently.

          Hopefully this solves your problem.

  • David Jaffe

    Hi, I have an issue/question around this. I’m attempting to connect to an API (, and am experiencing a “sporadic” issue. I’m able to get the user’s access tokens once, but after trying again a few times, I’m getting the “Not verified. Cannot get access tokens.”
    If I wait for a while (5-10 minutes) then try again, I am able to get the access tokens, then once again, I cannot until waiting.

    Additionally, the first time I attempt to get the tokens after waiting a few hours, it will fail (same spot – due to not being verified), then trying again after a few minutes works fine.

    Is this an issue with this website’s API itself? I’m not well versed in OAuth and tokens, so I’m not sure if I’m even doing it correctly. Every time my app loads, should I be re-performing the temp token -> user auth-> access tokens? Or should I somehow be reusing the same token each time?

    • Are you trying to get the access tokens more than once with the same verifier code? I think it is service dependent what the outcome in this situation would be, but it sounds like your service does not work so. You should only get the access token once for one verifier code. And then you should store that access token for upcoming requests (also when the app is being relaunched).

      From the library point of view, if you use the same verifier code for the requests when you can get the access token and also when you can’t get the access tokens, it doesn’t sound like a library issue. Also the error message leads me to believe that the issue is simply that the service does not recognize the verifier code that you are providing it. Of course there could be issue in getting the verifier code correctly, but if you verified that the code is indeed identical in both cases when you can get access token and when you can’t, then I can’t help much.

      And I’ve also learned that there can always be service specific OAuth surprises per service…

      • David Jaffe

        “You should only get the access token once for one verifier code. And then you should store that access token for upcoming requests (also when the app is being relaunched).”

        That makes SO much more sense. I used to work with the Facebook API in php a long time ago, so I never had to deal much with working with the tokens myself – for the most part, FBXML handled it. Thank you!

        • Glad I could help 🙂 Good luck!

        • David Jaffe

          One more question if you don’t mind. I’m going through the source and readme, but I can’t determine the correct way to rebuild the KOAuthManager upon re-loading an app. Should I just be directly setting all tokens / keys?

        • Yes. Your code should check if it already has an access token stored, if not, retrieve it. If your code already has the access token, no need to fetch it, but use it as you would after you fetched it for the previous case.

        • David Jaffe

          Gotcha, looked over some oauth doc and I see what you mean. So, specific to the library, on app load a KQOAuthRequest can be created, use setToken and setTokenSecret to rebuild it based on already gathered tokens, give it parameters, then use a KQAuthManager to execute the KQOAuthRequest?

        • Yep, something like that should work 🙂