Token

Secure JWE Token Utility for API Authorization

🔐 Note: Currently, this is the only authentication mechanism supported by expresso-macchiato. For version v1.0.0, introducing support for pluggable authentication strategies is a planned enhancement. 🧑‍💻 Contributions are welcome and highly encouraged!

The Token class is a developer-facing utility designed to manage encrypted tokens using the JWE (JSON Web Encryption) standard.

It provides methods to:

  • Generate secure encrypted tokens.

  • Authorize incoming HTTP requests via Bearer token.

  • Validate token expiration and structure.

  • Use a customizable secret key, expiration time, and encryption algorithm.

Internally, it uses node-jose and crypto to derive and manage the encryption key.

Constructor

new Token<Payload>(tokenPayload: TokenConstructor)

I raccomand you to put those values in env files.

  • SECRET_KEY (string) – Secret used to derive the encryption key. If not provided, a fallback key is used.

  • ExpTime (number) – Token expiration time in seconds.

  • EncAlgorithm (string) – JWE encryption algorithm (e.g. 'A256GCM', 'A128CBC-HS256').

Check node-jose official algorithms to chose wich one to use

  • KeyLength (number) – Length (in bytes) of the derived key (e.g. 32 for AES-256).

Methods

  • authorize(req: string | Request): Promise

You can pass directly the token or the full express request received in the apis)

Extracts the token from the Authorization header (Bearer <token>) and verifies it.

Use case: Middleware or route-level authorization in your API handlers.

Throws:

  • "UNAUTH" if no token is present.

  • "Token decryption failed" or "Token expired" on validation failure.

const tokenUtil = new Token({ ... });
const payload = await tokenUtil.authorize(req); // throws if invalid
  • generateJWE(payload: Payload): Promise

Generates a JWE (encrypted JWT) token from the provided payload, with iat (issued at) and exp (expiration) automatically injected.

Returns: A compact JWE string, ready to be used as a Bearer token.

Example:

tsCopiaModificaconst token = await tokenUtil.generateJWE({ userId: 123 });
res.setHeader('Authorization', `Bearer ${token}`);
  • verifyJWE(token: string): Promise

Decrypts and verifies a JWE token.

  • Validates expiration (exp) timestamp.

  • Throws on malformed or expired tokens.

Use case: Use internally when implementing custom token validation logic.

Example:

tsCopiaModificaconst payload = await tokenUtil.verifyJWE(tokenFromHeader);

Notes

  • This utility supports encryption-only tokens, not signed JWTs.

  • It is stateless – tokens are self-contained and don't require database lookups.

  • Best suited for microservices or API-first architectures that require tamper-proof tokens.

Last updated