【问题标题】:DRF "Unauthorized: <route>" when Authorization header is present from React FE当 React FE 中存在授权标头时,DRF“未授权:<route>”
【发布时间】:2021-02-16 08:30:21
【问题描述】:

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

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

我只是想了解几件事:

  1. Authorization 标头的存在显然告诉 DRF 它需要对其进行处理。是否需要在 DRF 设置中启用某些东西才能处理它?
  2. 我应该在POST 请求的标头或正文中将此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')

【问题讨论】:

    标签: reactjs django authentication django-rest-framework access-token


    【解决方案1】:

    我将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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-13
      • 1970-01-01
      • 2015-11-05
      • 1970-01-01
      • 2021-11-21
      • 2011-04-07
      • 2012-04-04
      • 2017-01-03
      相关资源
      最近更新 更多