Django Academy · Lección

Autenticación con tokens y JWT

Autentique clientes de API de forma segura

Lección 3 de 413 pasos

Autenticación con tokens y JWT es una lección gratuita de Django Academy en CoddyKit. Esta es la lección 3 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 Django Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Django Academy incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

APIs Need Stateless Auth

Browsers use sessions, but API clients often have no cookies. Token authentication lets a client prove who it is on every request instead.

How a Token Works

The user logs in once and gets a token string. They send it with each request, and DRF maps it back to the right user.

Enabling TokenAuthentication

Add the authtoken app and turn on TokenAuthentication so DRF knows to read tokens from incoming requests.

INSTALLED_APPS += ['rest_framework.authtoken']

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ],
}

Issuing a Token

DRF gives you a built-in obtain_auth_token view. Post a username and password to it, and it returns that user's token.

from rest_framework.authtoken.views import obtain_auth_token

urlpatterns = [
    path('api-token-auth/', obtain_auth_token),
]

Sending the Token

The client puts the token in the Authorization header, prefixed with the word Token, on every protected call. 🔑

Authorization: Token 9944b09199c62bcf9418ad846dd0e4

The Limit of Simple Tokens

A DRF token never expires and is just a database lookup. For larger systems, a JWT adds expiry and self-contained data.

What a JWT Carries

A JSON Web Token is a signed string holding claims like the user id and an expiry time. The server trusts it without a DB hit.

Adding SimpleJWT

Install djangorestframework-simplejwt and register its authentication class to swap tokens for JWTs.

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
}

Access and Refresh Tokens

SimpleJWT gives two tokens: a short-lived access token for requests and a longer refresh token to get a new access token.

JWT Login Endpoints

Wire up TokenObtainPairView to log in and TokenRefreshView to renew, and your JWT flow is ready.

from rest_framework_simplejwt.views import (
    TokenObtainPairView, TokenRefreshView)

urlpatterns = [
    path('token/', TokenObtainPairView.as_view()),
    path('token/refresh/', TokenRefreshView.as_view()),
]

Sending a Bearer Token

JWT clients use the Bearer scheme in the Authorization header instead of the Token word DRF tokens use. 🎟️

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

Quick Check

One key difference separates DRF tokens from JWTs.

Recap: Proving Identity

You learned to authenticate API clients with DRF tokens for simplicity and JWTs for expiry and scale, both sent in the Authorization header. 🎉

Gratis para empezar

Aprende Python con un tutor de IA — gratis

Escribe y ejecuta código real en tu navegador, obtén ayuda instantánea de un tutor de IA disponible 24/7 y continúa donde lo dejaste en la web o en la aplicación.

Cursos
30
Lecciones
120

Preguntas frecuentes

¿La lección «Autenticación con tokens y JWT» es gratis?

Sí — el texto completo de «Autenticación con tokens y JWT» 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 Django Academy, actualiza a CoddyKit PRO. El curso de Django Academy incluye 4 lecciones en total.

¿Qué aprenderé en «Autenticación con tokens y JWT»?

Autentique clientes de API de forma segura Practicas Django 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 Django Academy?

No se requiere experiencia previa. Django 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 3 de 4.

¿Cuánto tiempo toma la lección «Autenticación con tokens y JWT»?

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 Django Academy?

Sí. Cada lección de Django 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

  1. ModelViewSet y Routers
  2. Permisos y limitación de solicitudes
  3. Autenticación con tokens y JWT
  4. Filtrado, búsqueda y paginación
← Volver a Django Academy