Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Native Development

Reply
Developer
Posts: 120
Registered: ‎12-22-2011
My Device: ---

http digest authentication

Deas ,

 

I want a complete example show me how to make http digest authentication in BlackBerry 10 using QAuthenticator Class.

 

Can any one help me ?

Developer
Posts: 16,575
Registered: ‎07-29-2008
My Device: Z10 LE, Z30, Passport

Re: http digest authentication

As it is supported by QAuthenticator you can use it without any special code, just connect the authenticationRequired signal.
see
http://qt-project.org/doc/qt-4.8/qnetworkaccessmanager.html#authenticationRequired
----------------------------------------------------------
feel free to press the like button on the right side to thank the user that helped you.
please mark posts as solved if you found a solution.
@SimonHain on twitter
Developer
Posts: 120
Registered: ‎12-22-2011
My Device: ---

Re: http digest authentication

[ Edited ]

hi simon,

 

 

i tried this code but it doesn't call the authrequired signal , can you help me with this code 

 

// Default empty project template
#ifndef MainPage_HPP_
#define MainPage_HPP_

#include <bb/cascades/Application>
#include <QtCore/QObject>
#include <QtCore/QString>
#include <QtCore/QVariant>

#include <QtNetwork/QAuthenticator>
//#include <QAuthenticator>

using namespace bb::cascades;

namespace bb
{
    namespace cascades
    {
        class Application;
    }
}

/*!
 * @brief Application pane object
 *
 *Use this object to create and init app UI, to create context objects, to register the new meta types etc.
 */
class MainPage: public QObject
{
    Q_OBJECT
public:
    MainPage(bb::cascades::Application *app);
    virtual ~MainPage()
    {
    }

    Q_INVOKABLE
    void loginService(QString username, QString password);

    void requestNetwork(QString url, QString username, QString password);

    void parseXml(QByteArray xmlByte);

    void parseJSONArray(QString xmlByte);
    void parseJSONObject(QString xmlByte);

//	signals:
//	void requestFinished(QNetworkReply *reply);

public slots:
    void requestFinished(QNetworkReply *reply);
    void authRequired(QNetworkReply *reply, QAuthenticator *authenticator);
};

#endif /* MainPage_HPP_ */

 

// Default empty project template
#include "MainPage.hpp"

#include <bb/data/JsonDataAccess>
#include <bb/cascades/GroupDataModel>

#include <bb/cascades/Application>
#include <bb/cascades/Page>
#include <bb/cascades/QmlDocument>

using namespace bb::cascades;
using namespace bb::data;

static const QUrl url("auth url ");
static const char *user = "user_name ";
static const char *password = "password";

MainPage::MainPage(bb::cascades::Application *app) :
        QObject(app)
{
    // create scene document from main.qml asset
    // set parent to created document to ensure it exists for the whole application lifetime
    QmlDocument *qml = QmlDocument::create("asset:///main.qml").parent(this);
    qml->setContextProperty("mainObj", this);
    // create root object for the UI
    AbstractPane *root = qml->createRootObject<AbstractPane>();
    // set created root object as a scene
    app->setScene(root);
}

void MainPage::loginService(QString username, QString password)
{
    qDebug() << "user name : " << username << " password : " << password;



    QString url = QString("auth_url");
    requestNetwork(url, username, password);
}

/*
 * Code for Connecting to service
 */
/*!
 * @params mRequestParams a QUrl object used to store the parameters used by MyNetwork object while making post request.
 * @params mEmailTxtFld a reference to TextField control used to store the email address entered by user.
 * @params mPassTxtFld a reference to TextField control used to store the password entered by user.
 */
void MainPage::requestNetwork(QString url, QString username, QString password)
{
//	if (mEmailTxtFld && mEmailTxtFld->text() != NULL
//			&& mEmailTxtFld->text().length() > 0) {
//		qDebug() << "Email value " << mEmailTxtFld->text() << "  \n";
//		mRequestParams.addQueryItem("username", mEmailTxtFld->text());
//	}
//	if (mPassTxtFld && mPassTxtFld->text() != NULL
//			&& mPassTxtFld->text().length() > 0) {
//		qDebug() << "Pass value " << mPassTxtFld->text() << "  \n";
//		mRequestParams.addQueryItem("password", mPassTxtFld->text());
//	}

    QUrl mRequestParams = QUrl(url);
    mRequestParams.addQueryItem("user", username);
    mRequestParams.addQueryItem("password", password);
    mRequestParams.addQueryItem("method", "json");
//	try {

    /*!
     * @brief this object manages the whole network transaction(starting from request creation to response acceptance).
     */
    QNetworkAccessManager *networkManager = new QNetworkAccessManager(this);
    /*!
     * @brief this QUrl object is used as parameter to QNetworkRequest
     */
    QUrl requestUrl(url);
    /*!
     * @brief this QNetworkRequest object acts as a parameter to the post() method for making request to server.
     */
    QNetworkRequest request(requestUrl);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

    if (networkManager) {
        /*!
         * @brief this connect() method connects finished() Signal of QNetworkAccessManager object with the requestFinished() slot in this app context.
         */
//		bool resFromServer = connect(networkManager,
//				SIGNAL(finished(QNetworkReply*)), this,
//				SLOT(requestFinished(QNetworkReply*)));
        // Test_1
//        connect(networkManager,
//                SIGNAL(authenticationRequired(QNetworkReply*,QAuth enticator*)),
//                SLOT(authRequired(QNetworkReply*,QAuthenticator*)) );
        //Test_2
        connect(networkManager,SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
                SLOT(authRequired(QNetworkReply*,QAuthenticator*)));

//        qDebug() << "Connection is success : ? : " << resFromServer;
//        Q_ASSERT (resFromServer);
//        Q_UNUSED(resFromServer);

        /*!
         * @brief this object accepts the reply from server once request is made.
         */
        QNetworkReply *reply = networkManager->post(request, mRequestParams.encodedQuery());
        if (reply) {
            qDebug() << "Reply from server is " << reply;
        }
    }
//	} catch (bad_alloc& e) {
//		qDebug() << "Exception : " << e.what() << "\n";
//	} catch (bad_exception& ex) {
//		qDebug() << "Exception : " << ex.what() << "\n";
//	}
//	catch () {
//		qDebug() << "Unknown Exception Occurred \n";
//	}
}

void MainPage::authRequired(QNetworkReply *reply, QAuthenticator *authenticator)
{
    qDebug() << "realm" << Q_FUNC_INFO << authenticator->realm();
// get user name and password from user for authenticator->realm()
// if (not cancelled) set the details otherwise don't
    authenticator->setUser(user);
    authenticator->setPassword(password);
}

/*!
 * this SLOT method collects the reply from  server and handles it
 */
void MainPage::requestFinished(QNetworkReply *reply)
{
    /*!
     * @brief QString object to be used to store server response
     */
    QString response;

    if (reply) {
        if (reply->error() == QNetworkReply::NoError) {
            int available = reply->bytesAvailable();
            if (available > 0) {
                QByteArray buffer(reply->readAll());
                response = QString(buffer);
            } else
                response = "Zero bytes in response";

        } else {
            int httpStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
            response = "Error and the code is "
                    + reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString()
                    + "  And the Error string is :: " + reply->errorString() + "\n";
        }
        reply->deleteLater();
    } else {
        response = "Response comes out to be null";
    }

    if ((response.trimmed().isEmpty())) {
        response = "Empty Response";
    }
    qDebug() << "Response String is :: " << response << " \n";

    if (!response.isNull()) {
        // You got response . Do whatever you want to do with it.
        QTextCodec *codec = QTextCodec::codecForName("UTF-8");
        QByteArray encodedString = codec->fromUnicode(response);

//		parseXml(encodedString);
        parseJSONObject(response);
    }
}

void MainPage::parseXml(QByteArray xmlByte)
{

    /* QXmlStreamReader takes any QIODevice. */
    QXmlStreamReader xml(xmlByte);

    //	xml.addData(xmlByte); //xml is a QXmlStreamReader

    if (xml.hasError()) {
        qDebug() << "XML error: " << xml.errorString() << endl;
    } else {
        while (!xml.atEnd() && !xml.hasError()) {
            xml.readNext();
//			if (xml.isStartElement()) {
            QString name = xml.name().toString();
            if (name == "msg") {
                qDebug() << "element name: '" << name << "'" << ", text: '" << xml.readElementText()
                        << "'" << endl;
            }

//			}
        }
    }
}

void MainPage::parseJSONArray(QString mJsonData)
{

    GroupDataModel *model = new GroupDataModel(QStringList() << "msg");

    // Load the JSON data
    mJsonData = QString("[{\"msg\":\"teto_1\"},{\"msg\":\"teto_2\"}]");

    JsonDataAccess jda;

    QVariantList list = jda.loadFromBuffer(mJsonData).value<QVariantList>();

    // Add the data to the model
    model->insertList(list);

    qDebug() << model->size() << " ------------- " << list.size();

    for (int i = 0; i < list.size(); i++) {
        qDebug() << list.value(i).toMap().value("msg");
    }
}

void MainPage::parseJSONObject(QString mJsonData)
{
    JsonDataAccess jda;
    QVariant mainList = jda.loadFromBuffer(mJsonData);
    qDebug() << mainList.toMap().value("msg");
}

 

can you help me with the problem in this code ?

Developer
Posts: 120
Registered: ‎12-22-2011
My Device: ---

Re: http digest authentication

Dears,

I'm still looking for the solution. Any help ?

Developer
Posts: 16,575
Registered: ‎07-29-2008
My Device: Z10 LE, Z30, Passport

Re: http digest authentication

can you use your code to access a non-protected site like google.com?
I would suggest to go step by step and see where it actually breaks.
----------------------------------------------------------
feel free to press the like button on the right side to thank the user that helped you.
please mark posts as solved if you found a solution.
@SimonHain on twitter