How to Sign and Verify JWT License Keys for Python Apps
You shipped a Python app to a customer’s server. Somewhere in site-packages sits your licensing module, and the entire check is four readable lines and an if. Anyone with a text editor can change return False to return True and be done in under a minute — no decompiler required.
That’s the problem this article solves. Not “how do I add a license key field,” but how do you produce a license proof a customer can’t forge, and verify it inside code they can’t casually edit. We’ll cover what a JWT license actually contains, how ES256 signing works, and how to sign and verify licenses with Py2Native’s Pro plugin so the verification routine ends up as native machine code with the public key baked in.
Why JWT License Verification Matters for Python Apps
A license check has two jobs: prove the license is authentic, and prove it’s still valid. Both fail if the logic is stored as source.
- Authenticity requires a signature only you can produce. That means asymmetric crypto: you sign with a private key, the app verifies with a public key.
- Validity requires claims the app can read without calling home — issuer, audience, expiry, customer ID.
JSON Web Tokens give you both in one compact, self-contained string. The app needs no network access, no licensing server, and no database — just the token and a public key. That’s why JWT is a good fit for on-premise and air-gapped deployments.
But the verification routine itself is now the attack surface. If it lives in readable Python, an attacker doesn’t need to forge a JWT — they patch the check. The fix is to compile that logic into the binary, which is exactly what Py2Native does: it compiles your plain Python into native machine code using Cython under the hood, without you writing .pyx files, adding Cython syntax, or running a manual cythonize step. Third-party libraries are left unmodified and keep working as Python source.
What a License Proof Looks Like: JWT Structure and ES256
A JWT is three base64url-encoded parts joined by dots:
eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJSU0ogU29mdHdhcmUgR21iSCI... . <signature>
└──────────── header ───────────┘└──────────────── payload ──────────────┘
Decoded, the header names the algorithm:
{ "alg": "ES256", "typ": "JWT" }
And the payload carries the license claims:
{
"iss": "RSJ Software GmbH",
"aud": "TimestampGIT",
"sub": "acme-corp",
"iat": 1767225600,
"exp": 1798761600
}
The claims that matter for licensing:
iss— who issued the license. Your app should expect an exact value.aud— who the license is for. Lets you issue tokens per product or per customer environment.exp— expiry as a Unix timestamp. The single most useful enforcement lever you have.sub— the customer or deployment identifier, useful for logging and support.
ES256 is ECDSA over the NIST P-256 curve with SHA-256. It’s the right default for license signing: 64-byte signatures (small enough to paste into an email), fast verification, and no parameter choices to get wrong the way RSA padding schemes allow. The security model is simple — the private key never leaves your signing machine, and only the public key ships inside the compiled binary. A customer who extracts the public key learns nothing useful; they still can’t mint a token.
Step-by-Step: Signing and Verifying Licenses with Py2Native Pro
The open-source py2native core (MIT) handles compilation, uv embedding, and cross-platform builds. The py2nativepro plugin adds the JWT tooling: keygen, sign, show, and the --license build flag. All commands run through uv.
1. Generate an EC P-256 keypair
Do this once, on your signing machine:
uv run py2native keygen private.pem public.pem
Keep private.pem offline or on a hardened signing server. public.pem is safe to commit to your build pipeline — it’s meant to be distributed, just like the license tokens it validates.
2. Write the payload and sign it
Create the claims file you want to issue:
{
"iss": "RSJ Software GmbH",
"aud": "TimestampGIT",
"sub": "acme-corp",
"iat": 1767225600,
"exp": 1798761600
}
Then sign it into a JWT:
uv run py2native sign --private private.pem payload.json license.dat
license.dat is the token you ship to the customer. Regenerating it for a renewal is the same command with a new exp — no rebuild, no key rotation.
3. Declare the compiled entry point in a .pxd file
Verification lives in the _p2n_bootstrap module that Py2Native generates during the build. To call into it, add a .pxd file alongside the module that performs the check:
# license_check.pxd
from _p2n_bootstrap cimport _runtime_verify_es256_jwt
cdef _runtime_verify_es256_jwt(token, expected_iss=*, expected_aud=*)
The cimport pulls in the compiled ES256 verification routine; the cdef line pins its signature so your call compiles against the correct argument types. This is the one declaration file you touch when using Pro license verification — there are no Cython source files to write and no build scripts to maintain.
4. Call verification with the license key
# license_check.py
from pathlib import Path
from _p2n_bootstrap import _runtime_verify_es256_jwt
class LicenseError(RuntimeError):
"""Raised when a license token cannot be verified."""
def require_license(path: str = "license.dat") -> dict:
licenseString = Path(path).read_text(encoding="utf-8").strip()
license = _runtime_verify_es256_jwt(licenseString, expected_iss="RSJ Software GmbH", expected_aud="TimestampGIT")
return license
Then use it from your entry point like any other Python function:
# main.py
from license_check import LicenseError, require_license
def main() -> None:
claims = require_license()
print(f"Licensed to {claims['sub']} (expires {claims['exp']})")
# ... your application starts here
if __name__ == "__main__":
main()
Note the two pinned expectations: expected_iss and expected_aud. Those aren’t decoration — they’re what stops a token issued for a different product or a different vendor from unlocking your binary.
5. Build with the license baked in
uv run py2native build main.py *.py \
--license license.dat \
--public public.pem \
--wheel dist
The --license flag performs the Pro license check at build time, and --public bakes the public key plus the verification routine into the output. The resulting executable carries native code for the check; there’s no Python implementation of ES256 signature validation to find and patch. If you’d rather ship a shared library than an executable, add --library — the wheel builder produces the compiled .pyd/.so/.dylib together with the generated __init__.py (the meta-path finder that redirects import yourpkg.submodule into the shared library) and __main__.py (so python -m yourpkg still works).
6. Inspect the claims whenever support asks
uv run py2native show --public public.pem license.dat
This prints the JWT claims and, given the public key, verifies the signature — useful when a customer sends you a token and insists it should work.
Interpreting Verification Results and Handling Edge Cases
_runtime_verify_es256_jwt returns the decoded payload when the token is valid and raises an exception when it isn’t. The usual causes:
- Expired token —
expis in the past. Most common cause by far; usually just a lapsed renewal. - Clock skew — an on-premise server whose clock drifted. Worth documenting a tolerance in your support runbook before customers hit it.
- Issuer/audience mismatch — a token signed with the right key but issued for a different product or tenant. The
expected_iss/expected_audarguments catch this. - Tampered token — a modified payload, which invalidates the ES256 signature.
- Wrong key — a token signed with a different private key than the one matching the embedded public key.
Handle it explicitly rather than letting a stack trace reach the user:
# main.py
import sys
from license_check import LicenseError, require_license
def main() -> None:
try:
claims = require_license()
except LicenseError as exc:
print(f"License verification failed: {exc}", file=sys.stderr)
print("Install a valid license.dat next to the executable,", file=sys.stderr)
print("or contact your vendor to renew.", file=sys.stderr)
raise SystemExit(1)
print(f"Licensed to {claims['sub']} (expires {claims['exp']})")
if __name__ == "__main__":
main()
Because the verification routine is compiled and the public key is embedded in the executable, an attacker can’t simply open a .py file and short-circuit the return value. Monkey-patching is still theoretically possible — third-party libraries ship as ordinary Python source, and that’s a deliberate trade-off — but the crypto check itself raises the bar considerably over a pure-Python if.
Beyond the Basics: Security Considerations and Alternatives
You can do this the hard way: pull in PyJWT, write the jwt.decode(..., algorithms=["ES256"], audience=..., issuer=...) call yourself, and then figure out how to stop people from reading it. That works, and plenty of teams do it — but the verification logic stays readable Python unless you separately solve the code-protection problem, and you’re now carrying a crypto dependency in your shipped artifact.
The Pro plugin takes the other approach. Key generation, signing, and verification are handled by compiled code with no third-party crypto libraries involved, so there’s no dependency surface to audit and no Python-level ES256 implementation in the shipped binary. The split is clean: the MIT-licensed core compiles your code and manages the embedded uv environment, while py2nativepro adds JWT license verification and string compression.
If you’re weighing how much protection compilation actually buys you, the honest answer deserves its own article — see Is Compiled Python Really Unreadable?. For tool-by-tool comparisons and cost, see Cython vs Nuitka vs Py2Native and Python Code Protection Tools: What You Get for the Price.
FAQ
Can I use my own JWT library instead of Py2Native’s Pro plugin? Yes. Any JWT library works, and Py2Native will compile your code either way. The difference is that the verification logic stays as Python source and is easier to locate and bypass. The Pro plugin compiles the verification into native code and embeds the public key, which is meaningfully harder to defeat.
What happens if the license is invalid or expired?
_runtime_verify_es256_jwt raises an exception if the token is invalid, expired, or carries the wrong issuer or audience. Catch it and handle it gracefully — prompt the user to renew, write a clear message to stderr, and exit non-zero rather than tracing back into your application code.
Is the private key stored in the binary? No. Only the public key is embedded in the compiled executable. The private key stays on your signing machine or build server and is never distributed with the application.
How does Py2Native protect the verification logic from tampering? Py2Native compiles your Python — including the license check — into native machine code. The Pro plugin additionally bakes the public key and the ES256 verification routine into the executable, so there’s no readable Python signature check to patch and no key file sitting next to the binary waiting to be swapped.
Wrapping Up
Signing is the easy half: keygen once, sign per license. Verification is where the design decision lives, and the decision is whether the check is something an attacker can read. Pin expected_iss and expected_aud, handle the exception path so failures are legible to real customers, and compile the whole thing so the check ships as machine code rather than as a suggestion.
uv run py2native keygen private.pem public.pem
uv run py2native sign --private private.pem payload.json license.dat
uv run py2native build main.py *.py --license license.dat --public public.pem --wheel dist
Three commands from empty directory to a native binary that validates signed ES256 licenses offline. If you’re taking that to a fleet of on-premise installs, Python Licensing for On-Premise Deployments and Automate Compiling Python to Native Binaries in CI/CD cover the next steps.
Related posts
- Cython vs Nuitka vs Py2Native: Which Protects Python Code?
- Python Code Protection Tools: What You Get for the Price
- Is Compiled Python Really Unreadable? An Honest Look