Implementing JWT Signing and Verification
Overview
JSON Web Tokens (JWT) defined in RFC 7519 are compact, URL-safe tokens used for authentication and authorization in web applications. This skill covers implementing secure JWT signing with HMAC-SHA256, RSA-PSS, and EdDSA algorithms, along with verification, token expiration, claims validation, and defense against common JWT attacks (algorithm confusion, none algorithm, key injection).
When to Use
Trigger phrases:
"implementing jwt signing and verification"
"JSON Web Tokens (JWT) defined in RFC 7519 are compact, URL-safe tokens used for "
When deploying or configuring implementing jwt signing and verification capabilities in your environment
When establishing security controls aligned to compliance requirements
When building or improving security architecture for this domain
When conducting security assessments that require this implementation
Prerequisites
- Familiarity with cryptography concepts and tools
- Access to a test or lab environment for safe execution
- Python 3.8+ with required dependencies installed
- Appropriate authorization for any testing activities
Objectives
- Implement JWT signing with HS256, RS256, ES256, and EdDSA
- Verify JWT signatures and validate standard claims
- Implement token expiration, not-before, and audience validation
- Defend against algorithm confusion and none algorithm attacks
- Implement JWT key rotation with JWK Sets
- Build a complete authentication middleware
Key Concepts
This section covers key concepts for implementing jwt signing and verification.
- Ensure all prerequisites are met before proceeding
- Follow the documented workflow steps in sequence
- Record results and any anomalies encountered during this phase
JWT Algorithms
| Algorithm |
Type |
Key |
Security Level |
| HS256 |
Symmetric (HMAC) |
Shared secret |
128-bit |
| RS256 |
Asymmetric (RSA) |
RSA key pair |
112-bit |
| ES256 |
Asymmetric (ECDSA) |
P-256 key pair |
128-bit |
| EdDSA |
Asymmetric (Ed25519) |
Ed25519 pair |
128-bit |
Common JWT Attacks
- Algorithm confusion: Switching from RS256 to HS256, using public key as HMAC secret
- None algorithm: Setting alg=none to bypass signature verification
- Key injection: Embedding key in JWK header
- Weak secrets: Brute-forcing short HMAC secrets
- Token replay: Reusing valid tokens without expiration
Security Considerations
- Always validate the algorithm header against an allowlist
- Never accept alg=none in production
- Use asymmetric algorithms (RS256, ES256) for distributed systems
- Set short expiration times (15 min for access tokens)
- Implement token refresh mechanism
- Store secrets securely (not in source code)
Validation Criteria
When NOT to Use
- You need to test the implementation (use performing-* skills)
- Task is about configuring existing tools (use configuring-* skills)
- You need to analyze security events (use analyzing-* skills)
- Task is about building detection rules (use building-* skills)
- You don't have access to the target environment
- Task requires vendor-specific expertise (consult vendor docs)
Red Flags
- Performing actions without explicit written authorization from the asset owner
- Testing against production systems without a defined scope and rules of engagement
- Testing without rate limiting, potentially causing service degradation
- Storing sensitive test data (credentials, tokens) in plain text logs
- Using automated scanners blindly without reviewing results for false positives
Verification
- All steps executed successfully against a test environment before production use
- Output documented with screenshots or logs demonstrating expected behavior
- Vulnerabilities reproduced with proof-of-concept and impact analysis
- False positives filtered out through manual verification
- Fix recommendations include code-level remediation guidance
Process
# Example: IOC detection
import re
IOC_PATTERNS = {
"ip": r"\b(?:\d{1,3}\.){3}\d{1,3}\b",
"domain": r"\b[a-z0-9-]+\.[a-z]{2,}\b",
"hash_md5": r"\b[a-f0-9]{32}\b",
"hash_sha256": r"\b[a-f0-9]{64}\b",
}
def extract_iocs(text: str) -> dict:
return {k: re.findall(v, text) for k, v in IOC_PATTERNS.items()}
- Analyze the task requirements
- Apply domain expertise
- Verify output quality
Anti-Rationalization Table
| Rationalization |
Reality |
| "We are too small to be targeted" |
Automated attacks target everyone. Size does not matter. |
| "Security slows us down" |
A breach slows you down 100x more. Build security in from the start. |
| "We will fix it after launch" |
Vulnerabilities in production are exploited within hours. Fix before deploy. |
1---2name: implementing-jwt-signing-and-verification3description: Use when JSON Web Tokens (JWT) defined in RFC 7519 are compact, URL-safe4 tokens used for authentication and authorization in web applications. This skill5 covers implementing secure JWT signing with HMAC-SHA2566domain: cybersecurity7subdomain: cryptography8tags:9- cryptography10- jwt11- authentication12- token-security13- digital-signatures14version: '1.0'15author: oyi7716license: Apache-2.017nist_csf:18- PR.DS-0119- PR.DS-0220- PR.DS-1021category: cybersecurity22metadata:23 source: https://skillmd.com/skills/oyi77/implementing-jwt-signing-and-verification24---2526# Implementing JWT Signing and Verification2728## Overview2930JSON Web Tokens (JWT) defined in RFC 7519 are compact, URL-safe tokens used for authentication and authorization in web applications. This skill covers implementing secure JWT signing with HMAC-SHA256, RSA-PSS, and EdDSA algorithms, along with verification, token expiration, claims validation, and defense against common JWT attacks (algorithm confusion, none algorithm, key injection).313233## When to Use34**Trigger phrases:**35- "implementing jwt signing and verification"36- "JSON Web Tokens (JWT) defined in RFC 7519 are compact, URL-safe tokens used for "373839- When deploying or configuring implementing jwt signing and verification capabilities in your environment40- When establishing security controls aligned to compliance requirements41- When building or improving security architecture for this domain42- When conducting security assessments that require this implementation4344## Prerequisites4546- Familiarity with cryptography concepts and tools47- Access to a test or lab environment for safe execution48- Python 3.8+ with required dependencies installed49- Appropriate authorization for any testing activities5051## Objectives5253- Implement JWT signing with HS256, RS256, ES256, and EdDSA54- Verify JWT signatures and validate standard claims55- Implement token expiration, not-before, and audience validation56- Defend against algorithm confusion and none algorithm attacks57- Implement JWT key rotation with JWK Sets58- Build a complete authentication middleware5960## Key Concepts6162This section covers key concepts for implementing jwt signing and verification.6364- Ensure all prerequisites are met before proceeding65- Follow the documented workflow steps in sequence66- Record results and any anomalies encountered during this phase67### JWT Algorithms6869| Algorithm | Type | Key | Security Level |70|-----------|------|-----|---------------|71| HS256 | Symmetric (HMAC) | Shared secret | 128-bit |72| RS256 | Asymmetric (RSA) | RSA key pair | 112-bit |73| ES256 | Asymmetric (ECDSA) | P-256 key pair | 128-bit |74| EdDSA | Asymmetric (Ed25519) | Ed25519 pair | 128-bit |7576### Common JWT Attacks7778- **Algorithm confusion**: Switching from RS256 to HS256, using public key as HMAC secret79- **None algorithm**: Setting alg=none to bypass signature verification80- **Key injection**: Embedding key in JWK header81- **Weak secrets**: Brute-forcing short HMAC secrets82- **Token replay**: Reusing valid tokens without expiration8384## Security Considerations8586- Always validate the algorithm header against an allowlist87- Never accept alg=none in production88- Use asymmetric algorithms (RS256, ES256) for distributed systems89- Set short expiration times (15 min for access tokens)90- Implement token refresh mechanism91- Store secrets securely (not in source code)9293## Validation Criteria9495- [ ] JWT signing produces valid tokens for all algorithms96- [ ] Signature verification rejects tampered tokens97- [ ] Expired tokens are rejected98- [ ] Algorithm confusion attack is prevented99- [ ] None algorithm is rejected100- [ ] JWK key rotation works correctly101- [ ] Claims validation enforces all required claims102## When NOT to Use103104- You need to test the implementation (use performing-* skills)105- Task is about configuring existing tools (use configuring-* skills)106- You need to analyze security events (use analyzing-* skills)107- Task is about building detection rules (use building-* skills)108- You don't have access to the target environment109- Task requires vendor-specific expertise (consult vendor docs)110111112## Red Flags113114- Performing actions without explicit written authorization from the asset owner115- Testing against production systems without a defined scope and rules of engagement116- Testing without rate limiting, potentially causing service degradation117- Storing sensitive test data (credentials, tokens) in plain text logs118- Using automated scanners blindly without reviewing results for false positives119## Verification120121- All steps executed successfully against a test environment before production use122- Output documented with screenshots or logs demonstrating expected behavior123- Vulnerabilities reproduced with proof-of-concept and impact analysis124- False positives filtered out through manual verification125- Fix recommendations include code-level remediation guidance126127## Process128129```python130# Example: IOC detection131import re132133IOC_PATTERNS = {134 "ip": r"\b(?:\d{1,3}\.){3}\d{1,3}\b",135 "domain": r"\b[a-z0-9-]+\.[a-z]{2,}\b",136 "hash_md5": r"\b[a-f0-9]{32}\b",137 "hash_sha256": r"\b[a-f0-9]{64}\b",138}139140def extract_iocs(text: str) -> dict:141 return {k: re.findall(v, text) for k, v in IOC_PATTERNS.items()}142```1431441. Analyze the task requirements1452. Apply domain expertise1463. Verify output quality147148## Anti-Rationalization Table149150| Rationalization | Reality |151|---|---|152| "We are too small to be targeted" | Automated attacks target everyone. Size does not matter. |153| "Security slows us down" | A breach slows you down 100x more. Build security in from the start. |154| "We will fix it after launch" | Vulnerabilities in production are exploited within hours. Fix before deploy. |