Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 26, 2022 04:32 pm GMT

Configurando JWT en Django Rest Framework

Lo primero que tenemos que hacer es instalar simplejwt:

pip install djangorestframework-simplejwt

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

Django==4.0.0django-cors-headersdjango-getenvdjangorestframework==3.12.2psycopg2-binarydjangorestframework-simplejwt

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'),

En settings.py en las configuraciones de REST_FRAMEWORK definimos la autenticacin 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'    )}

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',]

Una vez hecho esto, en nuestras views podemos pedir que para que alguien haga una peticin hacia nuestro endpoint, como mnimo tiene que estar autenticado, y el mtodo de autenticacin que configuramos es el de JWT:

from django.http import JsonResponsefrom rest_framework import permissions, statusfrom rest_framework.decorators import api_view, permission_classes@api_view(["POST"])@permission_classes([permissions.IsAuthenticated])def create_post(request):    return JsonResponse({'msg': 'todo funcionando'})

Probando la configuracin:

  • Sin autenticacin:

Image description

  • Autenticndonos para obtener el token

Image description

  • Utilizando el token para hacer peticiones

Image description


Original Link: https://dev.to/nahuelsegovia/configurando-jwt-en-django-rest-framework-3nna

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To