我正在尝试将令牌传递到后端,但我遇到了一些问题。
当我在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