Search code examples
reactjsdjangoauthenticationdjango-rest-frameworkaccess-token

DRF "Unauthorized: <route>" when Authorization header is present from React FE


I'm working on integration with Azure AD. I have my ReactJS FE getting the accessToken and now I need to send it to the Django/DRF BE to authenticate it there as well.

At any rate, I'm sending the token as a Authorization: "Bearer <token>" and I'm getting a Unauthorized: <route> response. If I comment it out, the request goes through.

I'm just trying to understand a couple things:

  1. The presence of the Authorization header is obviously telling DRF it needs to do something with it. Does something need to be enabled in DRF settings to handle it?
  2. Should I be sending this accessToken to my API in the headers, or the body, of the POST request?
// Authentication.js
...
  const testApiAuthentication = async () => {
    let accessToken = await authProvider.getAccessToken();
    setAccessToken(accessToken.accessToken);
    if (accessToken) {
      setAuthenticatingToken(true);
      axios({
        method: 'post',
        url: '/api/users/',
        headers: {
          Authorization: 'Bearer ' + accessToken,
        },
      })
        .then((response) => {
          console.log(response);
        })
        .catch((error) => {
          console.log(error);
        });
    }
  };
...

# views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import AllowAny

# Create your views here.
class TestView(APIView):
    permission_classes = [AllowAny]

    def post(self, request, *args, **kwargs):
        print(request)
        return Response('Hello World')

Solution

  • I modified my TestView to the following and now I get a successful response from the API:

    from rest_framework.views import APIView
    from rest_framework.response import Response
    from rest_framework.permissions import AllowAny
    from rest_framework.authentication import TokenAuthentication
    
    # Create your views here.
    class TestView(APIView):
        authentication_classes = [TokenAuthentication]
        permission_classes = [AllowAny]
    
        def post(self, request, *args, **kwargs):
            print(request)
            return Response('Hello World')