Tokens Bearer y encabezados
Exija y lea un token de acceso en cada solicitud.
Tokens Bearer y encabezados es una lección gratuita de MCP Academy en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de MCP Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de MCP Academy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
What a Bearer Token Is
A bearer token is a secret string that means "whoever holds this is allowed in." The server trusts the holder, no password needed per call. 🎟️
The Authorization Header
Clients send the token in the HTTP Authorization header so it rides along with every request automatically.
The Bearer Prefix
The header value starts with the word Bearer, a space, then the token. That prefix tells the server which auth scheme is in use.
GET /mcp HTTP/1.1
Authorization: Bearer sk-7f3a9c2e8b1d4a6fReading the Header on the Server
Your MCP server pulls the Authorization value off the incoming request before handling the JSON-RPC body.
auth = request.headers.get("Authorization", "")
token = auth.removeprefix("Bearer ").strip()Compare, Then Decide
The server checks the token against what it expects. A match lets the request through; anything else is rejected.
if token != EXPECTED_TOKEN:
raise HTTPException(status_code=401)Use Constant-Time Comparison
Plain equality can leak timing hints. Use a constant-time compare so attackers cannot guess the token character by character.
import hmac
ok = hmac.compare_digest(token, EXPECTED_TOKEN)401 Means Not Authenticated
Return 401 Unauthorized when the token is missing or invalid. It signals the caller to supply valid credentials.
403 Means Not Allowed
Use 403 Forbidden when the caller is known but lacks permission for that action. It is a different answer than 401.
Keep Tokens Out of URLs
Never put the token in the query string. URLs land in logs and browser history, so the header is the safer home for secrets.
Store Secrets in the Environment
Read the expected token from an environment variable, never hardcoded in source. That keeps it out of your version control.
import os
EXPECTED_TOKEN = os.environ["MCP_TOKEN"]Rotate When in Doubt
If a token might be exposed, issue a new one and retire the old. Rotation limits how long a leaked secret stays useful.
Quick Check
Spot the correct header format.
Recap: One Header, One Check
Send the secret as Bearer in the Authorization header, compare it safely, and answer 401 when it fails. Simple and solid. ✅
Preguntas frecuentes
¿La lección «Tokens Bearer y encabezados» es gratis?
Sí — el texto completo de «Tokens Bearer y encabezados» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de MCP Academy, actualiza a CoddyKit PRO. El curso de MCP Academy incluye 4 lecciones en total.
¿Qué aprenderé en «Tokens Bearer y encabezados»?
Exija y lea un token de acceso en cada solicitud. Practicas MCP Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar MCP Academy?
No se requiere experiencia previa. MCP Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.
¿Cuánto tiempo toma la lección «Tokens Bearer y encabezados»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de MCP Academy?
Sí. Cada lección de MCP Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Por qué los servidores remotos necesitan autenticación
- Tokens Bearer y encabezados
- El flujo de OAuth en MCP
- Limitar las acciones de un token