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

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

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

Okay