Search code examples
djangodjango-rest-frameworkdjango-rest-framework-simplejwt

rest_framework_simplejwt post to an APIView


I have this settings:

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ]
}

And this view:

class Config(APIView):
    def get(self, request, *args, **kwargs):
        if 'config' in request.GET.dict():
            if os.path.isfile(settings.CONFIG):
                yaml = read_config(settings.CONFIG)
                return Response(yaml)
            else:
                return Response({
                    "success": False,
                    "error": "config file not found!"})
        else:
            return Response({"success": False})

    def post(self, request, *args, **kwargs):
        if 'data' in request.data:
            print(request.data['data'])

        return Response({"success": False})

With axios I manage my api calls, for example:

axios.post('api/config/?config', { data: obj, headers: { Authorization: 'Bearer ' + rootState.auth.jwtToken } })

The problem is now, that I can not post data. I get an Unauthorized (401) error and in the response message it says: {"detail":"Authentication credentials were not provided."}

Can you please tell me, what I'm missing here and how can I fix this issue?


Solution

  • 1- What is AUTH_HEADER_TYPES in settings.py ? Bearer or JWT. If JWT you must change header auth type.

    2- Did you provide authenticate and obtain token ?

    Solution:

    Axios Post request assumes that the second parameter is data and third parameter is config. you sent header in second parameter. you can set the headers in the config.

    axios.post(url, data, config)
    

    change your axios.post to:

    axios.post('api/config/?config', { data: obj }, {
    headers: { Authorization: 'Bearer ' + rootState.auth.jwtToken }})