Clavem

How to validate a license key in a Qt 6 app

POST the key and the saved instance id to /v1/licenses/validate with QNetworkAccessManager, read the status from HttpStatusCodeAttribute and the body even on 4xx, and emit one outcome signal. Store the key with QtKeychain, because QSettings is not a secret store.

Qt already gives you an event loop, networking and JSON, so the License API needs no extra library. This page is the online validate call and what to do with each answer. The Ed25519 check used for the offline path is in offline verification in Qt, and the first-run call is in device activation in Qt. A Qt-free C++ version with libcurl is in license key validation in C++.

The Qt code in this guide was not compiled or run, because no Qt installation was available. It uses documented Qt 6 APIs, and the server behavior it relies on was checked against the live API.

The client

One class, one signal. All network work is asynchronous, so the UI thread is never blocked:

// licenseclient.h
#pragma once
#include <QJsonObject>
#include <QNetworkAccessManager>
#include <QObject>
#include <optional>

class LicenseClient : public QObject {
  Q_OBJECT
 public:
  enum class Kind { Valid, NotValid, Unknown, NoAnswer };
  struct Outcome { Kind kind; QString token; QString reason; std::optional<int> retryAfter; };

  explicit LicenseClient(QObject* parent = nullptr, QUrl base = QUrl("https://clavem.io"))
      : QObject(parent), m_base(std::move(base)) {}

  void validate(const QString& key, const QString& instanceId);

 signals:
  void validated(const LicenseClient::Outcome& outcome);

 private:
  QNetworkAccessManager m_nam;
  QUrl m_base;
};
// licenseclient.cpp
#include "licenseclient.h"
#include <QJsonDocument>
#include <QNetworkReply>

void LicenseClient::validate(const QString& key, const QString& instanceId) {
  QJsonObject body{{"license_key", key}};
  if (!instanceId.isEmpty()) body["instance_id"] = instanceId;

  QNetworkRequest request(m_base.resolved(QUrl("/v1/licenses/validate")));
  request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
  request.setHeader(QNetworkRequest::UserAgentHeader, "Inkwell/3.2");
  request.setTransferTimeout(std::chrono::seconds(8));

  QNetworkReply* reply = m_nam.post(request, QJsonDocument(body).toJson(QJsonDocument::Compact));
  connect(reply, &QNetworkReply::finished, this, [this, reply] {
    reply->deleteLater();
    const int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();  // 0: no HTTP answer
    const QJsonObject json = QJsonDocument::fromJson(reply->readAll()).object();
    const QString message = json["error"].toString();          // null becomes an empty string: no exception
    bool ok = false;
    const int wait = reply->rawHeader("Retry-After").toInt(&ok);
    const std::optional<int> retryAfter = ok ? std::optional<int>(wait) : std::nullopt;

    Outcome outcome{Kind::NoAnswer, {}, {}, std::nullopt};
    if (status == 200 && json["valid"].isBool()) {
      outcome = {json["valid"].toBool() ? Kind::Valid : Kind::NotValid, json["token"].toString(), message, std::nullopt};
    } else if (status == 404) {
      outcome = {Kind::Unknown, {}, message, std::nullopt};
    } else if (status == 429 || status == 503) {
      outcome = {Kind::NoAnswer, {}, {}, retryAfter};
    }
    emit validated(outcome);
  });
}

Pass this as the context object of the lambda, so it does not run after the client is destroyed. QJsonValue::toString() returns an empty string for null, which suits this API: a successful reply has "error": null. That is a quiet advantage over libraries that throw on a null field.

What each answer means

Reply Kind What the app does
200, valid: true Valid Store the new token. This restarts the 14-day window.
200, valid: false NotValid Expired or disabled. Store the token, show the reason, keep the key.
404 Unknown Unknown key, or instance_id not found. Clear the license and ask for the key.
429, 503 NoAnswer No verdict. Use the stored token. retryAfter is 60 or 5 seconds.
Status 0 NoAnswer Offline, DNS failure, timeout or TLS failure. Same.

Here is a real response from the live API with the demo key, which the code above would turn into Kind::Valid. The reply also carries Cache-Control: no-store, so Qt’s HTTP cache never keeps a verdict.

{"valid":true,"error":null,"license_key":{"id":1,"status":"active","key":"S1GNE-TDEM0-7K4QX-9WZ2P-H5RB8","activation_limit":3,"activation_usage":1,"created_at":"2026-11-18T23:19:24.740Z","expires_at":null,"test_mode":false},"instance":null,"meta":{ ... },"token":"sgt1.eyJ2Ijo..."}

Where to keep the key

QSettings is the first thing Qt developers reach for, and it is the wrong tool. It writes a property list on macOS, the registry on Windows and an ini file on Linux, and the user can read and edit all of them. QtKeychain is the usual answer. It talks to the Keychain, Credential Manager and the Secret Service:

#include <qt6keychain/keychain.h>   // the header path depends on how QtKeychain was built

void saveSecret(const QString& name, const QString& value) {
  auto* job = new QKeychain::WritePasswordJob(QStringLiteral("com.example.inkwell"));
  job->setAutoDelete(true);
  job->setKey(name);
  job->setTextData(value);
  QObject::connect(job, &QKeychain::Job::finished, [](QKeychain::Job* j) {
    if (j->error()) qWarning() << "keychain write failed:" << j->errorString();
  });
  job->start();
}

The read and delete jobs follow the same pattern with ReadPasswordJob and DeletePasswordJob. Handle QKeychain::EntryNotFound as “no license saved”, and any other error as “no secure store”. On Linux without a Secret Service the job fails. Decide whether that blocks the app or falls back to a file with 0600 permissions.

Pitfalls specific to Qt

  • Check TLS at startup. Qt documents native backends, Schannel on Windows and Secure Transport on macOS, plus an optional OpenSSL backend. A deployment that lacks a working backend fails every HTTPS call. Log QSslSocket::supportsSsl() and QSslSocket::activeBackend() from a release build.
  • Create the QNetworkAccessManager in the thread that uses it. It needs that thread’s event loop. Do not call post from a worker thread you did not give an event loop.
  • Do not spin a nested QEventLoop to make the call synchronous. It reenters your UI code.
  • Retry a 503 once with a QTimer::singleShot, not a sleep. A 429 asks for 60 seconds: use the stored token and try again later.

Doing this with Clavem

The License API needs no secret, so nothing sensitive ships in the binary. Plan limits never block validation. See the API reference for every field.

Questions

Is QSettings safe for a license key?

No. QSettings writes to an ini file, a property list or the registry, all readable and editable by the user. Use a secret store such as QtKeychain, which uses the Keychain on macOS, Credential Manager on Windows and a Secret Service on Linux.

Why is the body empty when QNetworkReply reports an error for a 404?

It is not. QNetworkReply sets an error code for HTTP error statuses, but the body is still readable with readAll. Read HttpStatusCodeAttribute first, and treat the error code only as a hint when there was no HTTP answer.

How do I set a timeout on a Qt request?

Call setTransferTimeout on the QNetworkRequest. In Qt 6 it takes a std::chrono duration. The timeout aborts the reply, and finished then fires with an error and no HTTP status.

Sources

  1. Qt 6, QNetworkRequest, setTransferTimeout (checked November 2026)
  2. Qt 6, Secure Sockets Layer (SSL) classes (checked November 2026)