Express GraphQL with JWT

In this simple example, we have, step by step, how apply a security level with JWT to our API using GraphQL, how generate a token by JWT Debugger, as well how to make a call by postman .

1 – Fist of all, from the official GraphQL documentation, we have the “hello” example:

var express = require('express');
var { graphqlHTTP } = require('express-graphql');
var { buildSchema } = require('graphql');

var schema = buildSchema(`
  type Query {
    hello: String
  }
`);

var root = {
  hello: () => {
    return 'Hello world!';
  },
};

var app = express();
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
}));
app.listen(4000);
console.log('Running a GraphQL API server at http://localhost:4000/graphql');

2 – The graphiql: true config can be removed, due we can pass graphql body in postman. Then, we get the response:

3 – Now, as middleware, it is possible include JWT usage in our API:

npm install jsonwebtoken --save

In our example, jsonwebtoken is included as well the verifyToken JWT middleware, so we have:

var express = require('express');
var { graphqlHTTP } = require('express-graphql');
var { buildSchema } = require('graphql');

const jwt = require('jsonwebtoken');

var schema = buildSchema(`
  type Query {
    hello: String
  }
`);

var root = {
  hello: () => {
    return 'Hello world!';
  },
};

const verifyToken = (req, res, next) => {  
  jwt.verify(req.headers.authorization, 'mysecret', (err, decoded) => {
    console.log(decoded)
    if (err){      
      return res.sendStatus(401);
    }
    next();
  });
}

var app = express();

app.use(verifyToken);
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at http://localhost:4000/graphql');

If we try again request in postman /graphql, we get Status: 401 Unauthorized. Now, our API is protected under JWT, and a token is required.

4 – In debugger application at https://jwt.io, we can generate a token to pass in our request. We select HS256 algorithm, and we can pass our payload to our API too. Don’t forget input the correct secret ‘mysecret’ in Verify signature field.

5 – Finally, we just need to copy the token generated at https://jwt.io in Authorization header in our request at postman, and that’s it, we can access again our API:

You also can see our API log the payload passed:

As we can see, it is very simple protect our API under JWT, in advanced use, it is possible use pair of certificates, clients generate tokens programmatically, config expiration time, required token just for some resources, for others not, and so on.

Reflection in Qt

Reflection is a thecnical that lets us to handle object  indirectly by a meta object. It is particular kind of metaprogramming.
This program concept was born from object-oriented program(OOP), on every entity is handled as classes and objects are instances
of those. So, as everything in OOP is an object, A class can be treat as an object too. This object is known as metaobject. With the
metaobject we can manipulate every feature related to that class, like its consctructor, methods, attributes, and so on.
In this post, I would like to share a little dificult that I had to use reflection concept in Qt. It is just a “HelloWorld” example.
So, lets to the example!

For this example, I just implemented person.h, person.cpp and main.cpp. Below, it is the code and some commentaries.

person.h

/*
 * Here, we implemented Person class. In Qt, to use reflection, it is necessary
 * that class inherits QObject and uses Q_OBJECT macro. The inheritance due QObject
 * class provides staticMetaObject member. This is the meta object for our class.
 * With the Q_OBJECT macro, the meta object compiler(moc) creates another C++
 * source file where is implemented meta object code.
 */

#ifndef PERSON_H
#define PERSON_H

#include <QObject>

class Person : public QObject
{
	Q_OBJECT

public:
	Q_INVOKABLE Person(QString nome);
	QString getName();

private:
	QString _name;
};

#endif // PERSON_H

person.cpp

/*
 * Implementation of Person class.
 */
#include "person.h"

Person::Person(QString name)
{
	_name = name;
}

QString Person::getName()
{
	return _name;
}

main.cpp

/*
 * Main program.
 */
#include <QMetaObject>
#include <QDebug>
#include "person.h"

void anyMethod(QMetaObject metaObject)
{
	//We invoke the Person constructor through metaObject.
	Person *person = (Person *)metaObject
		.newInstance(Q_ARG(QString, QString("Sanderson")));
	QString name = person->getName();
	qDebug() << "Name: " << name;
}

int main()
{
	//Meta object to Person class. It is not a Person instance.
	anyMethod(Person::staticMetaObject);
	return 0;
}

Getting/Sending a dictionary through dbus with Qt

A little about DBus

DBus is message bus system, where applications can exchange information. This information can be, numbers, data structures, called function or just simple messages. By default there are two standard buses: session bus and system bus.

Session bus: It is generally used by desktop applications.

System bus: It used to the traffic of messages from the operating system kernel.

In this post, I’ve tried to explain how to call a remote function that returns a dictionary structure.

Scheme with applications and bus session.

Scheme with applications and bus session.

Connecting dbus session

To connect to DBus system, is needed to inform the system bus and the bus name. Bus name is name of the available service.

It is something like org.mycompany.service.

conn = QDBusConnection(QDBusConnection::connectToBus(QDBusConnection::SessionBus, DBUS_BUS_NAME));

Getting the interface

After connect to the bus, it must obtein the interface object, to send/receive message trough bus. To achieve this goal, the bus name, path object and interface name must be informed.

QDBusInterface iface(DBUS_BUS_NAME, DBUS_OBJECT_PATH, DBUS_INTERFACE, conn); p, li { white-space: pre-wrap; }

Getting the dictionary

Invoque the remote method GetOptions returning a dictionary to reply variable.

QDBusReply<QVariantMap> reply = iface.call(“GetOptions”);

Setting the dictionary

Invoke the remote method SetOptions, passing a dictionary as argument.

iface.call(“SetOptions”, protocolOptions);