AI 资讯
Connect a Local Developer Toolbox to Any MCP Assistant
If an AI assistant can write code but cannot reliably hash a value, inspect a JWT, validate JSON, or calculate a CIDR range, you have a small but recurring reliability problem. Asking the model to do those jobs from memory adds an unnecessary interpretation step. DevUtils MCP Server packages 36 everyday developer utilities behind the Model Context Protocol . The server runs locally over standard input and output, so an MCP-compatible client can call explicit tools instead of guessing an operation. This tutorial connects the released 1.1.0 package, verifies the protocol handshake, and shows how to choose a useful tool without treating the server as a replacement for application libraries. TL;DR Install Node.js 18 or newer, add the server command to your MCP client's configuration, restart the client, and ask it to use a tool such as json_validate , jwt_validate , or cidr_calculate . The smallest configuration is a command plus the package name: { "mcpServers" : { "devutils" : { "command" : "npx" , "args" : [ "devutils-mcp-server" ] } } } The released package declares Node.js >=18 . The repository's current default branch has moved ahead to 1.1.1 , so the commands and behavior in this article target the immutable v1.1.0 release and the npm latest package that was verified during research. Prerequisites You need: Node.js 18 or newer and npm. An MCP-compatible client that supports a local stdio server. Permission to run npx and download the public npm package on first use. No API key, account, database, or external service is needed for the local server. The MIT-licensed repository lists Claude Desktop, Cursor, VS Code, Windsurf, Docker, and other MCP-compatible clients as possible consumers. Their configuration file locations differ, but the server entry is the same. Install the released server The release README documents an npx path that does not require a global installation: npx devutils-mcp-server For an automated setup where accepting the package prompt must be e
AI 资讯
JWT auth without the confusion
The mental model that fixes everything JWT is just a token format . It is not authentication, not a session, and not a database. Once you separate those ideas, most of the pain disappears. A JWT is a JSON object that is signed. That's it. The payload holds claims like sub (subject) and exp (expiration). The signature proves the token wasn't tampered with. What JWT is not Not a session store : You can't revoke a JWT before it expires. If you need revocation, you need a blocklist or short expiry. Not a database : Don't stuff heavy data in the payload. It gets sent on every request. Not a magic bullet : It's a way to pass claims between parties without a shared server-side state. The three flows that matter 1. Access token only Simplest flow: login returns a JWT, client sends it in the Authorization header, server verifies it on every request. // server middleware (Express example) const jwt = require ( ' jsonwebtoken ' ); function auth ( req , res , next ) { const header = req . headers . authorization ; if ( ! header ) return res . status ( 401 ). json ({ error : ' No token ' }); const token = header . split ( ' ' )[ 1 ]; // Bearer <token> try { req . user = jwt . verify ( token , process . env . JWT_SECRET ); next (); } catch ( err ) { res . status ( 401 ). json ({ error : ' Invalid token ' }); } } Works fine for small apps, but every request hits your auth logic and the token can't be invalidated early. 2. Access + refresh token Common pattern for SPAs. Access token lives 15 minutes, refresh token lives 7 days. The refresh token is stored securely (httpOnly cookie) and used only to get a new access token. // issue tokens on login const accessToken = jwt . sign ({ userId }, process . env . JWT_SECRET , { expiresIn : ' 15m ' }); const refreshToken = jwt . sign ({ userId }, process . env . REFRESH_SECRET , { expiresIn : ' 7d ' }); res . json ({ accessToken }); res . cookie ( ' refreshToken ' , refreshToken , { httpOnly : true , secure : true , sameSite : ' strict ' })
AI 资讯
JWT Validation: Verifying Tokens for Authentication and Authorization
JWT Validation: Verifying Tokens for Authentication and Authorization A practical guide to JWT validation — the process of checking a JSON Web Token's signature, claims, and structure to confirm a request is genuinely authenticated and authorized — covering signature verification, standard claim checks, key rotation, validation in ASP.NET Core, and the mistakes that most commonly lead to broken or bypassed validation. Table of Contents Introduction Anatomy of a JWT Signing Algorithms What "Validation" Actually Checks Signature Verification and Key Rotation Standard Claim Validation Validating JWTs in ASP.NET Core Custom Validation Logic Token Revocation: JWT's Fundamental Limitation Validating JWTs Across Services Common Vulnerabilities Debugging Validation Failures Quick Reference Table Conclusion Introduction A JWT arriving in an Authorization: Bearer <token> header is just a string until it's actually validated — and validation is doing considerably more work than it might first appear. It's not just "does this look like a JWT" or even just "is the signature valid" — proper validation confirms the token was issued by a trusted party, intended for this specific API, still within its valid time window, and hasn't been tampered with in any way. Get any one of these checks wrong or skip it, and you can end up with an API that accepts tokens it absolutely shouldn't. builder . Services . AddAuthentication ( JwtBearerDefaults . AuthenticationScheme ) . AddJwtBearer ( options => { options . Authority = "https://login.microsoftonline.com/{tenant-id}/v2.0" ; options . Audience = "api://my-api" ; }); Those two lines look simple, but they configure a genuinely thorough validation pipeline underneath — this guide covers exactly what that pipeline actually checks, why each check matters, and where things commonly go wrong when validation is configured incorrectly or bypassed under pressure. 1. Anatomy of a JWT Three parts, dot-separated eyJhbGciOiJSUzI 1 NiIsInR 5 cCI 6 IkpXVC
AI 资讯
JWT Security Checklist: 12 Things to Verify Before You Ship
JWT authentication has more failure modes than most developers realise. Correct signature verification is necessary but far from sufficient. This checklist is what I run through before every production JWT deployment. 1. Secret Is Generated With a CSPRNG Not a password. Not a UUID. Not a timestamp. A cryptographically secure pseudorandom number generator output. In Node.js: crypto.randomBytes(32).toString('hex') In Python: secrets.token_hex(32) In the browser: jwtsecretgenerator.com/tools/jwt-secret-generator A 256-bit CSPRNG secret takes 10^59 years to brute force at current GPU speeds. 2. Algorithm Is Explicitly Specified in verify() // Wrong jwt . verify ( token , secret ); // Right jwt . verify ( token , secret , { algorithms : [ ' HS256 ' ] }); 3. exp Claim Is Present and Validated Short-lived tokens (15 minutes) limit the damage from leaks. Verify your library is actually checking exp — some require explicit configuration. 4. iss and aud Claims Are Validated Validates the token was issued by your service and intended for your API. Prevents token reuse across services. 5. Tokens Are in httpOnly Cookies, Not localStorage localStorage is readable by any script on the page. httpOnly cookies are invisible to JavaScript. 6. HTTPS Is Enforced JWT in a query parameter over HTTP is visible in every proxy, CDN, and server log on the path. Use the Authorization: Bearer header over HTTPS only. 7. Refresh Tokens Are Server-Side Revocable Short access tokens + server-side refresh tokens = the ability to end sessions immediately. Long-lived access tokens without refresh logic cannot be revoked. 8. The jti Claim Is Used If You Need Immediate Revocation Store revoked jti values in Redis with TTL matching token expiry. Check on every request. Adds one Redis lookup per request — worth it for high-security endpoints. 9. Different Secrets for Each Environment Dev secret leaks should not compromise production. Keep them separate. 10. Secret Is Not in Source Code or Version Control
开发者
I Audited 12 Open Source JWT Implementations and Found the Same 6 Mistakes
I spent last month reviewing JWT implementations across 12 open-source Node.js projects on GitHub — ranging from starter templates with 2k stars to production boilerplates used by teams at real companies. I found the same 6 mistakes in almost every one. None of these projects are bad. The developers are skilled. The mistakes are subtle, copy-paste errors from tutorials that nobody questioned. Here they are. Mistake 1 — The Secret Is Literally "secret" I found this in three separate projects: const token = jwt . sign ({ userId : user . id }, " secret " , { expiresIn : " 1h " }); This secret is in every JWT tutorial on the internet. It is in the jwt.io documentation. It is in the jsonwebtoken README. Developers copy it and forget to replace it. A 6-character ASCII secret has approximately 42 bits of entropy. A GPU cluster cracks it from a dictionary in milliseconds. Generate a real secret here — it takes 3 seconds and produces a 256-bit cryptographically random key. Mistake 2 — jwt.decode() Used in Auth Middleware // DANGEROUS — this is in a production auth middleware const decoded = jwt . decode ( req . headers . authorization . split ( " " )[ 1 ]); if ( ! decoded . userId ) return res . status ( 401 ). send ( " Unauthorized " ); jwt.decode() does not verify the signature. It reads the payload regardless of whether the token is valid, expired, or forged. An attacker can craft any payload they want and it will pass this check. The fix is two characters: jwt.verify() . const decoded = jwt . verify ( token , process . env . JWT_SECRET , { algorithms : [ " HS256 " ] }); Mistake 3 — Algorithm Not Specified in verify() // Missing algorithms option jwt . verify ( token , secret ); Without { algorithms: ['HS256'] } , the library trusts whatever algorithm is in the token's header. An attacker can create a token with alg: none and an empty signature — and jwt.verify() will accept it. Always specify the expected algorithm explicitly. Mistake 4 — Secret Committed to Version Cont
AI 资讯
FAM CTF : The Vault Door Writeup
Summary NexaVault is a mock internal dashboard app that gates an "Admin Vault" panel behind a role claim in a JWT. The app issues a user-role token on login, stored in the nx_access cookie, and trusts the claims inside it without properly re-verifying the signature on every request. Recon Logged in as a normal user ( strawhat ) and captured the request to /famctf/dashboard : Cookie: nx_access=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzdHJhd2hhdCIsInJvbGUiOiJ1c2VyIn0.x5PRC4_NFw5cGM02QklUN5yq6rtGOMP_E8bKGxgIbME Decoding the JWT: Header { "alg" : "HS256" , "typ" : "JWT" } Payload { "sub" : "strawhat" , "role" : "user" } The dashboard UI showed an "Admin Vault" card locked behind Admin only , confirming role was the authorization check. Attempt 1 - Naive tampering (failed) Editing the payload directly to "role":"admin" while keeping the original HS256 signature predictably failed - the signature no longer matched the modified payload, and the server redirected to the login page. This confirmed the server does verify the signature against the payload, but didn't yet confirm how strictly it verifies the algorithm itself. Attempt 2 - alg:none bypass (success) Many JWT libraries historically honor the alg field declared in the token header to decide how to verify, including a none algorithm meant for unsigned/pre-verified tokens. If the server-side verification doesn't explicitly reject none , an attacker can forge any payload with zero knowledge of the signing secret. Forged header: { "alg" : "none" , "typ" : "JWT" } Forged payload: { "sub" : "strawhat" , "role" : "admin" } Forging Script import base64 , json def b64url ( data : bytes ) -> str : return base64 . urlsafe_b64encode ( data ). rstrip ( b ' = ' ). decode () header = { " alg " : " none " , " typ " : " JWT " } payload = { " sub " : " strawhat " , " role " : " admin " } h = b64url ( json . dumps ( header , separators = ( ' , ' , ' : ' )). encode ()) p = b64url ( json . dumps ( payload , separators = ( ' , ' ,
AI 资讯
How Do You Log Someone Out of a Stateless System? JWT Invalidation on Logout
JWTs are one of those technologies that feel wonderful right up until you hit your first "log me out" requirement. Then you discover the awkward truth: the very property that makes JWTs attractive — statelessness — is also what makes logout hard. This post walks through what JWTs actually are, why "invalidating" one is a design problem rather than a one-liner, and the practical methods available to revoke an access token on logout, along with the bottleneck each one introduces. A quick refresher on JWTs A JSON Web Token (JWT) is a signed, self-contained token. It carries a JSON payload of claims — who the user is, when the token was issued, when it expires, and often a unique token id ( jti ) — and a cryptographic signature over that payload. Because the token is signed with a secret (or a private key), any server holding the corresponding key can verify it is authentic and untampered without calling a database . That last part is the entire point. When a request arrives with a JWT, the server checks the signature and the expiry, reads the claims, and proceeds. No lookup, no shared session store, no round trip. This is what people mean when they call JWT auth stateless : the server keeps no per-user session record. The token itself is the session, and it's valid until it expires. Access tokens and refresh tokens In practice you rarely use a single token. The common pattern splits responsibility across two: The access token is the short-lived workhorse. It's sent on every API request and typically expires in minutes (5–15 is common). Because it's checked statelessly on every call, you want its lifetime short — if it leaks, the damage window is small. The refresh token is long-lived (days or weeks) and does one job: obtain new access tokens when the current one expires. It is not sent on every request — only to a dedicated token endpoint. This lets the access token stay short and stateless while the user avoids logging in every ten minutes. The refresh token is easy —
AI 资讯
🚀 JWT sem hash forte de senha é armadilha — Argon2 + .NET fecham o ciclo
A stack de autenticação em .NET fica sólida quando separamos duas responsabilidades: ✅ Argon2id para guardar senhas (hash irreversível, lento, memória-intensivo) ✅ JWT Bearer para provar identidade depois do login ✅ Validação de iss , aud , exp e assinatura em cada request ✅ Segredos fora do repositório (ambiente / Key Vault) Se o ecossistema .NET já oferece hosting, APIs e pacotes maduros, combinar Argon2 (referência da Password Hashing Competition , testável em argon2.online ) com JWT é o caminho natural para microsserviços e Web APIs. Neste artigo, mostro o fluxo registo → login → token → rotas protegidas com foco no que implementar no dia a dia. ⚠️ Observação importante JWT não substitui Argon2. Nunca coloque senha ou hash no payload do token. Argon2 protege a credencial na base de dados; JWT é sessão assinada com expiração. 🧠 Visão Geral Aspecto Argon2 (senha) JWT (sessão) Foco Resistir a offline cracking Autorizar requests após login Onde vive Coluna password_hash na BD Header Authorization: Bearer Algoritmo Argon2id (OWASP) HMAC-SHA256 ou RSA (config) Ferramenta de estudo argon2.online docs Microsoft JWT Bearer Runtime Biblioteca .NET (ex.: Konscious Argon2) Microsoft.AspNetCore.Authentication.JwtBearer Erro clássico MD5/SHA rápido na senha Token sem validar aud / iss 🧩 O que o Argon2 resolve (camada 1) O Argon2 é o vencedor da Password Hashing Competition — hoje a referência para novas passwords . 1️⃣ Hash irreversível com Argon2id var hash = hasher . Hash ( password ); await store . CreateAsync ( email , hash ); ✅ Salt único por utilizador ✅ Parâmetros m , t , p documentados no próprio hash ✅ Verificação com tempo constante ( FixedTimeEquals ) 2️⃣ Calibrar custo com consciência Em argon2.online podes experimentar memory cost e iterations — útil em laboratório. 📌 Em produção usa biblioteca auditada (.NET), não hashes de utilizadores reais em sites públicos. 3️⃣ O que não fazer na senha ✅ Não “criptografar” senha com AES reversível ✅ Não MD5 / SHA-1 / SHA-256
AI 资讯
Your JWT decoder might be leaking your tokens. Here's how to check.
Most developers paste production JWTs into online decoders without thinking. Here's a 10-second DevTools check to see if your token is actually leaving your machine. A coworker was debugging an auth bug last month. Standard workflow: copy the JWT from the failing request, paste it into an online decoder, read the payload. I've done it a thousand times. You probably have too. Except the token he pasted belonged to a real customer. And the decoder he used is owned by an identity company that's had its share of security incidents. Nothing bad happened. Probably. But it made me think about something I'd never actually checked: when you paste a JWT into an online decoder, where does that token go? What a JWT actually contains Quick reminder of why this matters. A JWT isn't encrypted — it's just Base64URL-encoded. Anyone who has the token can read everything in it: header.payload.signature The payload routinely contains: User ID, email, and role Session identifiers Token expiry ( exp ) and issue time ( iat ) Sometimes — against best practice — far more And here's the part people forget: a valid, unexpired JWT is a live credential. If it hasn't expired, whoever holds it can often impersonate the user. Pasting it into a random website is functionally similar to pasting a password. The 10-second check Most online JWT decoders claim to be "secure" and "client-side." Some are. Some aren't. You don't have to trust the claim — you can verify it yourself in 10 seconds: Open the decoder in your browser Open DevTools → Network tab Clear the network log Paste a JWT and decode it Watch the Network tab If any request fires when you decode — your token left your machine. A truly client-side decoder fires zero network requests during decoding. The JavaScript does everything locally; nothing is sent anywhere. Try this on whatever decoder you currently use. You might be surprised. Why most "online" tools send data It's usually not malicious. Building decoding logic on the server is someti