Search code examples
qturlencodeqbytearrayqurl

Qt QUrlQuery extract Qbytearray token


Possible duplicate Question

I am generating a reset link/token that will be emailed to the client as follows.

    QByteArray token;
    token.resize(crypto_pwhash_SALTBYTES);
    randombytes_buf(token.data(), crypto_pwhash_SALTBYTES);

    QUrlQuery token_url("http://localhost:8080/reset/staff");
    token_url.addQueryItem("token", token);
    token_url.query(QUrl::FullyEncoded).toUtf8();

This appears to produce the correct output:

http://localhost:8080/reset/staff&token=pc%22%EF%BF%BD%C6%9Fsktx%EF%BF%BD!%06t%5C%0B

To authenticate the reset request against the stored hash I need the token QByteArray.

QByteArray path = request.getPath();
qDebug() << path;

QUrlQuery token_url(path);
QString token(token_url.queryItemValue("token"));
qDebug() << token;

qDebug() << QUrl::fromPercentEncoding(path);

The output including the pasted url in firefox is gibberish

"/reset/staff&token=pc\"\xEF\xBF\xBD\xC6\x9Fsktx\xEF\xBF\xBD!\x06t\\\x0B"
"pc\"�Ɵsktx�!%06t\\%0B"
"/reset/staff&token=pc\"�Ɵsktx�!\u0006t\\\u000B"

I understand I'm probably doing a doggy unsigned char Converstion.

What is the elegant method for passing QBytearrays in and out of QUrlQuery?

I have seen some programmers writing their own URL parsers but that seems excessive.


Solution

  • [SOLVED] Problem was with QtWebApps HttpRequest::decodeRequestParams() the Url was being double decoded additionally QUrlQuery.query() doesn't work quiet as you would expect.

    K.I.S.S Encode your URL manually

    QByteArray url("http://localhost:8080/reset/staff?");
    url.append("&token="+token.toPercentEncoding());
    
    qDebug() << url; 
    

    On the receiving end

    split the query from "?"
    then split at "&" into key=value pairs
    then split at "=" 
    finally QByteArray::fromPercentEncoding(key)
    finally QByteArray::fromPercentEncoding(value)
    

    I am open to improvements if anyone has got a more elegant solution.