Skip to content

Not responding to requests using form-data #463

Open
@elrulreloaded

Description

we have a Django installation using JWT Token, which it was working correctly answering request with form-data. From three weeks now using Postman, pytest or curl if we make a request using JSON it answers correctly returning the token as expected. However, if data is changed to data answer is always unsupporter gran type.
This behavior started to show three weeks ago with new instalations.

This is the actual pytest, we change json for data and that changes the

import pytest
import random
import string
import pprint
import json
import sys
@pytest.mark.test_1
def test_01():
    """ Generación de token
    """ 
    headers = {
      "alg": "HS256",
      "typ": "JWT"
        }

    data =  {
        "grant_type":"password",
        "client_id":"PDN4ci0l",
        "client_secret":"PlatafrmaDig",
        "scope":"read write",
        "username":"plataforma",
        "password":"[email protected]",
    }

    response = requests.post(
        url= "http://127.0.0.1/o/token/",#MODIFICA URL AQUI
        data=data,
        headers=headers
    ).json()

    print(str(response))
    with open('data.json', 'w', encoding='utf-8') as f:
        json.dump(response, f, ensure_ascii=False, indent=4)
    print(response)

as shown it returns always unsupported grant type, changing data for json in line 34 it returns token.

THis is the code of our view, it has been working so our assumption is that in some new version there is something that blocks the process of formdata request.

This is the settings part of rest framework

REST_FRAMEWORK = {
   'DEFAULT_AUTHENTICATION_CLASSES': [
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication'
   ],
   'DEFAULT_PARSER_CLASSES':[
        'rest_framework.parsers.FormParser',
    ]

}

We also assume that it might be a configuration problem, but we have made an extensive research of code using log and nothing yet.
View,py code follows

import json, subprocess

from django.http import HttpResponse
from django.core import serializers as serializers_django
from django.contrib.auth import authenticate
from django.contrib.auth.models import User

from django.views.decorators.csrf import csrf_exempt

from declaracion.models import Declaraciones,CatTiposDeclaracion,InfoPersonalFija
from django.contrib.auth.models import User

from django.http import JsonResponse
from rest_framework_simplejwt.authentication import JWTTokenUserAuthentication
from .utils import *
from .serialize_functions import serialize_declaracion, serialize_response_entry
from .validator import get_token_from_request, token_not_expired

from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.decorators import api_view, permission_classes, authentication_classes
from rest_framework import status, permissions, serializers, generics
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.generics import RetrieveAPIView
from rest_framework_simplejwt.views import TokenObtainPairView
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework_simplejwt import views as jwt_views
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer

from oauth2_provider.views.generic import ProtectedResourceView
from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope, TokenHasScope

from declaraciones.settings import EXPIRES_IN_N_MINUTES
from datetime import timedelta

from rest_framework.parsers import JSONParser
from rest_framework import serializers


from decimal import Decimal
from datetime import datetime, date
from sitio.models import sitio_personalizacion
import logging

default_page = 1
default_size = 10
max_page_size = 200
empty_json_error_auth = '{ "detail": "Credenciales no autorizadas." }'
empty_json_error_auth = json.loads(empty_json_error_auth)
log = logging.getLogger(__name__)


class OauthDeclaraciones(ProtectedResourceView):

    def dispatch(self, request, *args, **kwargs):
        log.debug("en dispatch de entrada "+str(request.content_type))
        log.debug(str(request.data))
        
        # let preflight OPTIONS requests pass
        if request.method.upper() == "OPTIONS":
            return super().dispatch(request, *args, **kwargs)

        # check if the request is valid and the protected resource may be accessed
        valid, r = self.verify_request(request)

        if valid:
            request.resource_owner = r.user
            return super().dispatch(request, *args, **kwargs)
        else:
            return JsonResponse({"codigo": "700", "descripcion":"token expirado"})

    def post(self, request, *args, **kwargs):
        log.debug('o aqui')
        declaraciones = Declaraciones.objects.filter(cat_estatus=4)
        log.debug(request)
        try:
            json_data = json.loads(request.body)
        except Exception as e:
            return JsonResponse(res_400_error())

        #t_expired= False
        #if t_expired :
        #   response=json.loads('{"code":"700", "description":"Token expirado"}')
        #   return JsonResponse(response)


        
        data = super().post(request, *args, **kwargs)
        data.data["token_type"] =  "Bearer"
        data.data["expires_in"] = EXPIRES_IN_N_MINUTES * 60
        return data

Any tip or hint will be greatly appretiated, and apologize if this is not the proper forum to post.
Regards

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions