An Interest In:
Web News this Week
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
April 26, 2022 04:32 pm GMT
Original Link: https://dev.to/nahuelsegovia/configurando-jwt-en-django-rest-framework-3nna
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:
- Autenticndonos para obtener el token
- Utilizando el token para hacer peticiones
Original Link: https://dev.to/nahuelsegovia/configurando-jwt-en-django-rest-framework-3nna
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To