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-safe tokens used for authentication and authorization in web applications. This skill covers implementing secure JWT signing with HMAC-SHA2564license: Apache-2.05---67# Implementing JWT Signing and Verification89## Overview1011JSON 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).121314## When to Use15**Trigger phrases:**16- "implementing jwt signing and verification"17- "JSON Web Tokens (JWT) defined in RFC 7519 are compact, URL-safe tokens used for "181920- When deploying or configuring implementing jwt signing and verification capabilities in your environment21- When establishing security controls aligned to compliance requirements22- When building or improving security architecture for this domain23- When conducting security assessments that require this implementation2425## Prerequisites2627- Familiarity with cryptography concepts and tools28- Access to a test or lab environment for safe execution29- Python 3.8+ with required dependencies installed30- Appropriate authorization for any testing activities3132## Objectives3334- Implement JWT signing with HS256, RS256, ES256, and EdDSA35- Verify JWT signatures and validate standard claims36- Implement token expiration, not-before, and audience validation37- Defend against algorithm confusion and none algorithm attacks38- Implement JWT key rotation with JWK Sets39- Build a complete authentication middleware4041## Key Concepts4243This section covers key concepts for implementing jwt signing and verification.4445- Ensure all prerequisites are met before proceeding46- Follow the documented workflow steps in sequence47- Record results and any anomalies encountered during this phase48### JWT Algorithms4950| Algorithm | Type | Key | Security Level |51|-----------|------|-----|---------------|52| HS256 | Symmetric (HMAC) | Shared secret | 128-bit |53| RS256 | Asymmetric (RSA) | RSA key pair | 112-bit |54| ES256 | Asymmetric (ECDSA) | P-256 key pair | 128-bit |55| EdDSA | Asymmetric (Ed25519) | Ed25519 pair | 128-bit |5657### Common JWT Attacks5859- **Algorithm confusion**: Switching from RS256 to HS256, using public key as HMAC secret60- **None algorithm**: Setting alg=none to bypass signature verification61- **Key injection**: Embedding key in JWK header62- **Weak secrets**: Brute-forcing short HMAC secrets63- **Token replay**: Reusing valid tokens without expiration6465## Security Considerations6667- Always validate the algorithm header against an allowlist68- Never accept alg=none in production69- Use asymmetric algorithms (RS256, ES256) for distributed systems70- Set short expiration times (15 min for access tokens)71- Implement token refresh mechanism72- Store secrets securely (not in source code)7374## Validation Criteria7576- [ ] JWT signing produces valid tokens for all algorithms77- [ ] Signature verification rejects tampered tokens78- [ ] Expired tokens are rejected79- [ ] Algorithm confusion attack is prevented80- [ ] None algorithm is rejected81- [ ] JWK key rotation works correctly82- [ ] Claims validation enforces all required claims83## When NOT to Use8485- You need to test the implementation (use performing-* skills)86- Task is about configuring existing tools (use configuring-* skills)87- You need to analyze security events (use analyzing-* skills)88- Task is about building detection rules (use building-* skills)89- You don't have access to the target environment90- Task requires vendor-specific expertise (consult vendor docs)919293## Red Flags9495- Performing actions without explicit written authorization from the asset owner96- Testing against production systems without a defined scope and rules of engagement97- Testing without rate limiting, potentially causing service degradation98- Storing sensitive test data (credentials, tokens) in plain text logs99- Using automated scanners blindly without reviewing results for false positives100## Verification101102- All steps executed successfully against a test environment before production use103- Output documented with screenshots or logs demonstrating expected behavior104- Vulnerabilities reproduced with proof-of-concept and impact analysis105- False positives filtered out through manual verification106- Fix recommendations include code-level remediation guidance107108## Process109110```python111# Example: IOC detection112import re113114IOC_PATTERNS = {115 "ip": r"\b(?:\d{1,3}\.){3}\d{1,3}\b",116 "domain": r"\b[a-z0-9-]+\.[a-z]{2,}\b",117 "hash_md5": r"\b[a-f0-9]{32}\b",118 "hash_sha256": r"\b[a-f0-9]{64}\b",119}120121def extract_iocs(text: str) -> dict:122 return {k: re.findall(v, text) for k, v in IOC_PATTERNS.items()}123```1241251. Analyze the task requirements1262. Apply domain expertise1273. Verify output quality128129## Anti-Rationalization Table130131| Rationalization | Reality |132|---|---|133| "We are too small to be targeted" | Automated attacks target everyone. Size does not matter. |134| "Security slows us down" | A breach slows you down 100x more. Build security in from the start. |135| "We will fix it after launch" | Vulnerabilities in production are exploited within hours. Fix before deploy. |