DEV Community

Nahuel Segovia
Nahuel Segovia

Posted on

8 1

Configurando JWT en Django Rest Framework

Lo primero que tenemos que hacer es instalar simplejwt:

pip install djangorestframework-simplejwt
Enter fullscreen mode Exit fullscreen mode

en este caso yo lo tengo configurado junto a mi archivo requirements.txt:

Django==4.0.0
django-cors-headers
django-getenv
djangorestframework==3.12.2
psycopg2-binary
djangorestframework-simplejwt
Enter fullscreen mode Exit fullscreen mode

Una vez instalada la dependencia vamos a nuestro proyecto, y en urls.py agregamos las siguientes rutas:

path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
Enter fullscreen mode Exit fullscreen mode

En settings.py en las configuraciones de REST_FRAMEWORK definimos la autenticación que vamos a usar por defecto con el framework:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),

    'DEFAULT_PERMISSIONS_CLASSES':(
        'rest_framework.permissions.IsAuthenticated'
    )
}
Enter fullscreen mode Exit fullscreen mode

Sin olvidarnos que en INSTALLED_APPS tenemos que indicar que vamos a usar rest_framework:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
]
Enter fullscreen mode Exit fullscreen mode

Una vez hecho esto, en nuestras views podemos pedir que para que alguien haga una petición hacia nuestro endpoint, como mínimo tiene que estar autenticado, y el método de autenticación que configuramos es el de JWT:

from django.http import JsonResponse
from rest_framework import permissions, status
from rest_framework.decorators import api_view, permission_classes


@api_view(["POST"])
@permission_classes([permissions.IsAuthenticated])
def create_post(request):
    return JsonResponse({'msg': 'todo funcionando'})
Enter fullscreen mode Exit fullscreen mode

Probando la configuración:

  • Sin autenticación:

Image description

  • Autenticándonos para obtener el token

Image description

  • Utilizando el token para hacer peticiones

Image description

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay