Basic authentication with Qt (QNetworkAccessManager)
Asked Answered
H

3

16

I was trying to perform basic authentication for Twitter from my Qt app. I use QNetworkAccessManager. But I couldn't find any help on this.

But I found a program called qsoapmanager which passes credentials in base64 through the header. Maybe I can do this with QNAM by setting header in QNetowrkRequest. But I failed to find a way.

In qsoapman source, header is set like this:

QHttpRequestHeader header;

header.setValue( "Authorization", QString( "Basic " ).append( auth.data() ) );

Can I do just that with QNAM/QNReq or is there a better way?

Huggermugger answered 3/10, 2009 at 5:2 Comment(0)
R
12

The recommended way is to connect to the authenticationRequired signal and set the credentials from there.

Rigi answered 3/10, 2009 at 7:41 Comment(0)
H
45

But if you want to do it by just setting the header value, here's how you can do that:

// HTTP Basic authentication header value: base64(username:password)
QString concatenated = username + ":" + password;
QByteArray data = concatenated.toLocal8Bit().toBase64();
QString headerData = "Basic " + data;
request.setRawHeader("Authorization", headerData.toLocal8Bit());
Hogwash answered 9/11, 2009 at 12:40 Comment(1)
this way of doing it will prove useful in case of REST services that use basic authentication: the qauthenticator approach depends on doing an extra initial trip for server to ask for authentication, but using it in the aforementioned way, this trip can be avoided. thanks for this answer.Contagious
R
12

The recommended way is to connect to the authenticationRequired signal and set the credentials from there.

Rigi answered 3/10, 2009 at 7:41 Comment(0)
S
4

Just using qNetworkAccessManager normally but add

setRawHeader("Authorization", headerData.toLocal8Bit());

to your request.

Example:

//authentication

QString concatenated = "admin:admin"; //username:password

QByteArray data = concatenated.toLocal8Bit().toBase64();

QString headerData = "Basic " + data;

QNetworkRequest request=QNetworkRequest(QUrl("http://192.168.1.10/getinfo"));

request.setRawHeader("Authorization", headerData.toLocal8Bit());

networkAccessManager->get(request);

`

Spheroidal answered 14/2, 2017 at 8:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.