【问题标题】:django rest framework problems with passing the headerdjango rest框架传递标头的问题
【发布时间】:2020-10-20 09:15:44
【问题描述】:

我正在尝试将令牌传递到后端,但遇到了一些问题。

当我在 cmd 中写这个时:

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

我得到想要的用户。

但是当我从邮递员/前端发送请求时,我收到了这个错误:

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

这是我在前端的服务

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;
    };
};

当我发送请求时,在 XHR - 网络中,我在查询字符串参数中看到它,如下所示: headers: {"Authorization":"Token 50633f123efeb7b3f122e5e3ee4e9206463dfa5b413cacca475ab9ffd743da8f"}

这是邮递员的图片

这是我的设置.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

这里是 TodoViewSet,它也使用令牌,但除非我从 cmd 发送 req + 令牌,否则它不起作用。

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)

这里是 GetUserView

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

【问题讨论】:

    标签: django django-rest-framework http-headers django-rest-framework-jwt django-rest-knox


    【解决方案1】:

    您可以上传授权中的内容(邮递员)并检查令牌类型是否正确。

    【讨论】:

      【解决方案2】:

      当我在 axios 中添加默认授权标头时,它现在可以工作了:

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

      _getToken 函数只是以这种格式Token ${token} 从 localStorage 返回令牌 您可以将其更改为 Bearer ${token}JWT ${token},以便与您的 jwt 插件一起使用。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-05
      • 1970-01-01
      • 2017-03-12
      • 1970-01-01
      • 2022-08-14
      相关资源
      最近更新 更多