### Install JWT for Nim Library Source: https://github.com/katehonz/jwt-nim-baraba/blob/main/examples/README.md Instructions for installing the JWT for Nim library using the nimble package manager. This is a prerequisite for running any of the provided JWT examples. ```bash # Install JWT library nimble install jwt ``` -------------------------------- ### Install Nim and JWT Library (Bash) Source: https://github.com/katehonz/jwt-nim-baraba/blob/main/examples/README.md This snippet shows how to install a specific version of Nim and check if the JWT library is installed using nimble. It's useful for setting up the development environment. ```bash # Ensure Nim 2.2.0+ is installed choosenim install 2.2.0 # Check JWT library installation nimble list jwt ``` -------------------------------- ### Run All Nim JWT Examples Source: https://github.com/katehonz/jwt-nim-baraba/blob/main/examples/README.md Provides a sequence of commands to compile and run all the JWT examples included in the project. This allows for a comprehensive test of the library's capabilities. ```bash # Basic example nim c -r examples/basic_jwt.nim && echo "" # RSA example nim c -r examples/rsa_jwt.nim && echo "" # Web API example nim c -r examples/web_api_auth.nim && echo "" # Security example nim c -r examples/security_best_practices.nim ``` -------------------------------- ### Compile and Run Nim JWT Examples Source: https://github.com/katehonz/jwt-nim-baraba/blob/main/examples/README.md Demonstrates how to compile and run a specific JWT example file using the Nim compiler. This is the standard method for executing the provided code snippets. ```bash nim c -r examples/basic_jwt.nim ``` -------------------------------- ### Run JWT Examples in Nim Source: https://github.com/katehonz/jwt-nim-baraba/blob/main/README.md Commands to compile and run the example JWT applications provided in the nim-jwt library. These examples cover basic usage, RSA signatures, and web API authentication scenarios. ```bash nim c -r examples/basic_jwt.nim nim c -r examples/web_api_auth.nim ``` -------------------------------- ### Set Nim Version Source: https://github.com/katehonz/jwt-nim-baraba/blob/main/examples/README.md Command to install a specific version of Nim (2.2.0 or later) using the choosenim tool, ensuring compatibility with the JWT for Nim library. ```bash # Ensure Nim 2.2.0+ choosenim install 2.2.0 ``` -------------------------------- ### Install JWT Library via Nimble Source: https://github.com/katehonz/jwt-nim-baraba/blob/main/README.md Installs the nim-jwt library using the Nimble package manager. Ensure you have Nim 2.0.0 or later and the BearSSL library installed. ```bash nimble install jwt ``` -------------------------------- ### Basic JWT Creation and Verification in Nim Source: https://github.com/katehonz/jwt-nim-baraba/blob/main/examples/README.md Demonstrates the fundamental JWT functionality in Nim, including creating tokens with custom claims, signing them using HMAC, and verifying their integrity. This example is useful for understanding the core operations of the JWT library. ```nim import jwt import times let secretKey = "your-super-secret-key" # Create claims var claims = newClaims() claims["sub"] = newStringClaim("1234567890") claims["name"] = newStringClaim("John Doe") claims["iat"] = newTimeClaim(getTime()) claims["exp"] = newTimeClaim(getTime() + 1.hours) # Create token let token = createToken(secretKey, HS256, claims) echo "Token created: ", token # Verify token let verificationResult = verifyToken(token, secretKey) echo "Token valid: ", verificationResult.isValid if verificationResult.isValid: echo "Subject: ", verificationResult.claims.get("sub") echo "Name: ", verificationResult.claims.get("name") echo "Expires: ", verificationResult.claims.get("exp", "N/A") else: echo "Token verification failed." ``` -------------------------------- ### Build JWT Library from Source Source: https://github.com/katehonz/jwt-nim-baraba/blob/main/README.md Clones the nim-jwt repository and installs it locally using Nimble. This method is useful for development or when using the latest unreleased features. ```bash git clone https://github.com/yglukhov/nim-jwt.git cd nim-jwt nimble install -y ``` -------------------------------- ### Recommended Build Configuration (Nim) Source: https://github.com/katehonz/jwt-nim-baraba/blob/main/docs/MIGRATION.md Suggests compiler options for enhanced security and optimization when building projects that use the jwt-nim library. These are recommended for production environments. ```nim # In your project's .nimble file or build script # Enable security-focused compiler options # --checks:on --warnings:on # For production # -d:release --opt:size ``` -------------------------------- ### Nim: Configure Secure Key Sizes Source: https://github.com/katehonz/jwt-nim-baraba/blob/main/docs/MIGRATION.md Provides examples for configuring secure key sizes for HMAC and RSA algorithms in Nim. For HMAC, a minimum of 32 bytes is recommended, and for RSA, a minimum of 2048 bits is required. ```nim # HMAC: minimum 32 bytes let hmacKey = "your-32-byte-secret-key-here-1234567890" # 44+ characters # RSA: minimum 2048 bits # Generate with: openssl genpkey -algorithm RSA -out private.pem -pkeyopt rsa_keygen_bits:2048 ``` -------------------------------- ### RSA Signed JWT with PEM Keys in Nim Source: https://github.com/katehonz/jwt-nim-baraba/blob/main/examples/README.md Illustrates how to use RSA for signing and verifying JWTs in Nim, utilizing PEM formatted public and private keys. This example highlights the use of key identifiers for managing key rotation and emphasizes algorithm security. ```nim import jwt import times # Assume publicKey.pem and privateKey.pem are available let publicKey = readFile("publicKey.pem") let privateKey = readFile("privateKey.pem") var claims = newClaims() claims["sub"] = newStringClaim("user123") claims["iat"] = newTimeClaim(getTime()) claims["exp"] = newTimeClaim(getTime() + 1.hours) # Create token with RSA private key let token = createToken(privateKey, RS256, claims) echo "RSA Signed Token: ", token # Verify token with RSA public key let verificationResult = verifyToken(token, publicKey) echo "Token valid: ", verificationResult.isValid if verificationResult.isValid: echo "Subject: ", verificationResult.claims.get("sub") else: echo "Token verification failed." ``` -------------------------------- ### Change JWT Algorithm in Nim Source: https://github.com/katehonz/jwt-nim-baraba/blob/main/examples/README.md Illustrates how to change the signing algorithm for a JWT in Nim. This example shows replacing HS256 with RS384, demonstrating flexibility in algorithm selection. ```nim # In any example, change the algorithm let algorithm = RS384 # Instead of HS256 ``` -------------------------------- ### Bash: Update BearSSL Dependency Source: https://github.com/katehonz/jwt-nim-baraba/blob/main/docs/MIGRATION.md Shows the bash commands to refresh Nimble package dependencies and install the latest version of the BearSSL library, which may be necessary for resolving dependency conflicts. ```bash # Update to latest BearSSL nimble refresh nimble install bearssl@#head ``` -------------------------------- ### Nim: Set Appropriate Expiration Times for Tokens Source: https://github.com/katehonz/jwt-nim-baraba/blob/main/docs/MIGRATION.md Provides examples in Nim for setting appropriate expiration times for JWTs, differentiating between short-lived access tokens and longer-lived refresh tokens for better security and performance. ```nim # Short tokens for better security and performance claims["exp"] = newTimeClaim(getTime() + 15.minutes) # Access token claims["exp"] = newTimeClaim(getTime() + 7.days) # Refresh token ``` -------------------------------- ### Authorization Header Example (Nim) Source: https://github.com/katehonz/jwt-nim-baraba/blob/main/docs/SECURITY.md Shows the standard 'Authorization' header format using a Bearer token. It also highlights the security risk of transmitting tokens via query parameters. ```nim # Standard Authorization header format let headers = newHttpHeaders({ "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." }) # Never use query parameters for sensitive tokens # BAD: /api/users?token=eyJhbGciOiJIUzI1NiIs..." ``` -------------------------------- ### Create JWT Token (Nim) Source: https://github.com/katehonz/jwt-nim-baraba/blob/main/docs/MIGRATION.md Demonstrates how to create a basic JWT token with header and claims using the jwt library. This function is backward compatible between v0.x and v2.0. ```nim import jwt, json, tables var token = toJWT(%*{ "header": {"alg": "HS256", "typ": "JWT"}, "claims": {"sub": "1234567890", "name": "John Doe"} }) token.sign("secret") echo $token ``` -------------------------------- ### Web API Authentication with JWT in Nim Source: https://github.com/katehonz/jwt-nim-baraba/blob/main/examples/README.md Simulates a realistic web API authentication flow in Nim, including user login, access and refresh token generation, and protecting API endpoints. This example demonstrates how to manage user sessions and token lifecycles in a web context. ```nim import jwt import times let secretKey = "your-api-secret-key" proc login(username, password): (string, string) = # In a real app, verify username and password against a database if username == "admin" and password == "password": var accessTokenClaims = newClaims() accessTokenClaims["sub"] = newStringClaim("1") accessTokenClaims["username"] = newStringClaim(username) accessTokenClaims["exp"] = newTimeClaim(getTime() + 15.minutes) let accessToken = createToken(secretKey, HS256, accessTokenClaims) var refreshTokenClaims = newClaims() refreshTokenClaims["sub"] = newStringClaim("1") refreshTokenClaims["type"] = newStringClaim("refresh") refreshTokenClaims["exp"] = newTimeClaim(getTime() + 24.hours) let refreshToken = createToken(secretKey, HS256, refreshTokenClaims) return (accessToken, refreshToken) else: raise newException(ValueError, "Invalid credentials") proc protectedApiCall(token): Claims = let verificationResult = verifyToken(token, secretKey) if verificationResult.isValid: return verificationResult.claims else: raise newException(ValueError, "Unauthorized") # Example Usage try: let (accessToken, refreshToken) = login("admin", "password") echo "Access Token: ", accessToken echo "Refresh Token: ", refreshToken let userClaims = protectedApiCall(accessToken) echo "User ID: ", userClaims.get("sub") echo "Username: ", userClaims.get("username") echo "API call successful!" except ValueError as e: echo "Error: ", e.msg ``` -------------------------------- ### RSA Signing and Verification with Nim Source: https://github.com/katehonz/jwt-nim-baraba/blob/main/docs/CRYPTOGRAPHY.md Demonstrates how to sign a JWT using an RSA private key and verify it with a public key in Nim. Requires the privateKeyPem and publicKeyPem variables to be defined. ```nim # RS256 usage let header = %*{"alg": "RS256", "typ": "JWT", "kid": "rsa-2048-001"} var token = initJWT(header, claims) token.sign(privateKeyPem) # Verification with public key let isValid = token.verify(publicKeyPem, RS256) ``` -------------------------------- ### JWT Security Best Practices in Nim Source: https://github.com/katehonz/jwt-nim-baraba/blob/main/examples/README.md Explores advanced security features and patterns for JWTs in Nim, including secure key generation, token blacklisting for replay protection, and key rotation. This example demonstrates comprehensive security validation and attack scenario simulations. ```nim import jwt import times import strutils # Secure key generation (example) let secretKey = generateRandomKey(32) # 32 bytes for HS256 echo "Generated secure HMAC key: ", secretKey # Token blacklisting (conceptual - requires external storage like Redis or DB) var blacklistedTokens = newHashSet[string]() proc createSecureToken(key: string, algorithm: Algorithm, claims: Claims, issuer: string, audience: string, keyId: string): string = var tokenClaims = claims tokenClaims["iss"] = newStringClaim(issuer) tokenClaims["aud"] = newStringClaim(audience) tokenClaims["jti"] = newStringClaim(newUUID().str) tokenClaims["iat"] = newTimeClaim(getTime()) tokenClaims["exp"] = newTimeClaim(getTime() + 1.hours) return createToken(key, algorithm, tokenClaims, keyId=keyId) proc verifySecureToken(token: string, key: string, expectedAudience: string): VerificationResult = if blacklistedTokens.contains(token): return VerificationResult(isValid: false, error: "Token is blacklisted") let result = verifyToken(token, key) if result.isValid and result.claims.get("aud") == expectedAudience: return result else: return VerificationResult(isValid: false, error: "Verification failed") # Example Usage let issuer = "your-secure-app.com" let audience = "api.example.com" let keyId = "key-2023-12-001" var claims = newClaims() claims["sub"] = newStringClaim("user-123") let token = createSecureToken(secretKey, HS256, claims, issuer, audience, keyId) echo "Created valid token: ", token let verificationResult = verifySecureToken(token, secretKey, audience) echo "Token validation successful for user: ", verificationResult.claims.get("sub") echo " Algorithm: ", verificationResult.claims.get("alg") echo " Audience: ", verificationResult.claims.get("aud") echo " Key ID: ", verificationResult.claims.get("kid") echo " JWT ID: ", verificationResult.claims.get("jti") echo "Verification result: ", verificationResult.isValid # Simulate replay attack blacklistedTokens.incl(token) let replayResult = verifySecureToken(token, secretKey, audience) echo "Replay attempt result: ", replayResult.isValid if not replayResult.isValid: echo "Security Alert: Token replay detected" ``` -------------------------------- ### ECDSA Signing and Verification with Nim Source: https://github.com/katehonz/jwt-nim-baraba/blob/main/docs/CRYPTOGRAPHY.md Shows how to sign a JWT using an ECDSA private key and verify it with the corresponding public key in Nim. Optimized for performance-critical scenarios. ```nim # ES256 usage for performance-critical applications let header = %*{"alg": "ES256", "typ": "JWT", "kid": "ec-p256-001"} var token = initJWT(header, claims) token.sign(ecPrivateKeyPem) # Verification let isValid = token.verify(ecPublicKeyPem, ES256) ``` -------------------------------- ### Token Blacklisting Implementation (Nim) Source: https://github.com/katehonz/jwt-nim-baraba/blob/main/docs/SECURITY.md A Nim example demonstrating a basic token blacklisting mechanism using a HashSet to store used token IDs (jti) and their expiry times. This helps prevent replay attacks. ```nim type TokenBlacklist = object usedTokens: HashSet[string] expiry: Time proc addToBlacklist(blacklist: var TokenBlacklist, jti: string, exp: Time) = blacklist.usedTokens.incl(jti) # Clean up expired entries periodically ``` -------------------------------- ### Session Storage Example (Nim) Source: https://github.com/katehonz/jwt-nim-baraba/blob/main/docs/SECURITY.md A Nim object definition for server-side session storage, linking session data to a JWT ID (jti). This approach centralizes session management and can improve security. ```nim # Store minimal session data server-side type Session = object userId: string createdAt: Time lastActivity: Time jti: string # Link to JWT ID ``` -------------------------------- ### Nim: Optimize Algorithm Selection for Performance Source: https://github.com/katehonz/jwt-nim-baraba/blob/main/docs/MIGRATION.md Recommends algorithm choices for JWTs in Nim based on performance. ES256 is suggested as faster than RSA, and HS256 is the fastest for symmetric keys. ```nim # For high-performance scenarios let algorithm = ES256 # Faster than RSA # or let algorithm = HS256 # Fastest for symmetric keys ``` -------------------------------- ### Generate HMAC Key using OpenSSL (Bash) Source: https://github.com/katehonz/jwt-nim-baraba/blob/main/docs/CRYPTOGRAPHY.md Demonstrates how to generate HMAC keys of different sizes (256-bit and 384-bit) using the OpenSSL command-line tool. The output is in hexadecimal format. ```bash # Generate 32-byte (256-bit) key openssl rand -hex 32 # Generate 48-byte (384-bit) key openssl rand -hex 48 ``` -------------------------------- ### Test Basic JWT Functionality (Nim) Source: https://github.com/katehonz/jwt-nim-baraba/blob/main/docs/MIGRATION.md Nim code snippets for testing basic JWT token creation and verification. These tests ensure the core functionality works as expected after migration. ```nim # Test basic token creation test "basic token creation": var token = toJWT(testData) token.sign(testSecret) check $token != "" test "basic token verification": let token = tokenString.toJWT() check token.verify(testSecret, HS256) ``` -------------------------------- ### Generate RSA Private Key (Bash) Source: https://github.com/katehonz/jwt-nim-baraba/blob/main/docs/CRYPTOGRAPHY.md Generates a 3072-bit RSA private key using OpenSSL. This key is used for signing JWTs with RSA-based algorithms. ```bash openssl genpkey -algorithm RSA -out private_key.pem -pkeyopt rsa_keygen_bits:3072 ``` -------------------------------- ### Verify JWT Token (Nim) Source: https://github.com/katehonz/jwt-nim-baraba/blob/main/docs/MIGRATION.md Shows how to verify a JWT token using a secret key and algorithm. Version 2.0 includes enhanced security checks during verification. ```nim let token = tokenString.toJWT() let isValid = token.verify("secret", HS256) ``` -------------------------------- ### Benchmark JWT Token Verification (Nim) Source: https://github.com/katehonz/jwt-nim-baraba/blob/main/docs/MIGRATION.md A Nim procedure to benchmark the performance of JWT token verification. This helps in measuring the performance impact of the library's security enhancements. ```nim import times proc benchmarkVerification(iterations: int) = let start = cpuTime() for i in 0..