I'm trying to pass the token to the backend but I'm having some issues.

when I'm writing this in the cmd:

curl -H "Authorization: Token 3c9c6079602737a04fcb6b2e737804142ef93930e4e705c0598b2fc597759f7f"  http://127.0.0.1:8000/api/auth/user/

I get the user like I wanted.

but when I'm sending the request from the postman / frontend, I get this error:

{
    "detail": "Authentication credentials were not provided."
}

here is my service at the frontend

const config = {headers: {Authorization: `Token ${token}`}}

async function query() {
    try { 
        return await axios.get(`http://127.0.0.1:8000/api/${types.TODO_API}/`, null, config);
    } catch (err) {
        throw err;
    };
};

when I'm sending the req, in the XHR - Networks I see it in query string params like this: headers: {"Authorization":"Token 50633f123efeb7b3f122e5e3ee4e9206463dfa5b413cacca475ab9ffd743da8f"}

here is an image of postman image of the req in postman

here is my setting.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'corsheaders',
    'todo',
    'user',
    'knox'
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES':  (
        'knox.auth.TokenAuthentication',
    )
}

REST_KNOX = {
    'TOKEN_TTL': timedelta(hours=10000),
    'USER_SERIALIZER': 'knox.serializers.UserSerializer',
}

CORS_ALLOW_HEADERS = [
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
    'access-control-allow-origin',
]

CORS_ALLOW_CREDENTIALS = True

here is the TodoViewSet, which also use the token, but not working unless i send the req + token from the cmd.

class TodoViewSet(viewsets.ModelViewSet):
    permission_classes = (permissions.IsAuthenticated, )
    serializer_class = TodoSerializer

    def get_queryset(self):
        return self.request.user.todo.all()

    def preform_create(self, serializer):
        serializer.save(owner = self.request.user)

here is the GetUserView

class GetUserView(generics.RetrieveAPIView):
    permission_classes = (permissions.IsAuthenticated,)    
    serializer_class = UserSerializer
    
    def get_object(self):
        return self.request.user

score:0

its working now when I added default Authorization header in axios:

axios.defaults.headers.common['Authorization'] = _getToken();

the _getToken function just returns the token from localStorage in this format Token ${token} you can change it to Bearer ${token} or JWT ${token} so it will work with your jwt plugin.

score:1

can you upload whats in authorization(postman) and you check if the token type is correct.


Related Query