当 React FE 存在授权 header 时,DRF "Unauthorized: <route>"

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

我正在研究与 Azure AD 的集成。我的 ReactJS FE 获得了 accessToken,现在我需要将它发送到 Django/DRF BE 以在那里对其进行身份验证。

无论如何,我将令牌作为 Authorization: "Bearer <token>" 发送,并且我收到了 Unauthorized: <route> 响应。如果我将其注释掉,请求就会通过。

我只是想了解一些事情:

  1. Authorization header 的存在显然是在告诉 DRF 它需要对它做些什么。是否需要在 DRF 设置中启用某些东西来处理它?
  2. 我应该在 POST 请求的 header 或 body 中将此 accessToken 发送到我的 API 吗?
// 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')

我将 TestView 修改为以下内容,现在我从 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')