Django rest-auth Token 认证

标签 django reactjs django-rest-framework react-redux axios

我正在尝试使用 axios 从/rest-auth/user/页面获取信息。这是我的功能:

export const fetchUser = () => {
  const token = localStorage.getItem('token');
  return dispatch => {
    dispatch(fetchUserPending());
    axios.get('http://localhost:8000/api/v1/rest-auth/user/', {headers: { 'authorization': `Bearer ${token}`}})
      .then(response => {
        const user = response.data;
        dispatch(fetchUserFulfilled(user));
      })
      .catch(err => {
        dispatch(fetchUserRejected(err));
      })
  }
}

它使用我从登录中获得的 django token ,该 token 存储在 localStorage 中。我收到错误状态 403,未提供身份验证凭据。我尝试编辑我的 django settings.py 文件以包含

REST_FRAMEWORK = {
   'DEFAULT_AUTHENTICATION_CLASSES': [
       'rest_framework.authentication.TokenAuthentication',
   ],
} 

然后我收到未经授权的错误代码 401。谁能指导我正确的方向?谢谢!

最佳答案

默认情况下 rest_framework.authentication.TokenAuthentication 使用关键字 Token 而不是 Bearer。调用应该是:

axios.get('http://localhost:8000/api/v1/rest-auth/user/', {headers: { 'Authorization': `Token ${token}`}})

关于Django rest-auth Token 认证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53192681/

相关文章:

database - 将设置保存在数据库中

python - 求和 Django 中的记录值

javascript - 如何在react js中操作字符串变量

javascript - 在 React Native 移动应用程序中存储用户凭据的位置

javascript - 错误 "google.charts.load() cannot be called more than once with version .45 or earlier"

python - Django Rest 订购自定义

python - 类型错误 : 'method' object is not iterable MySQL

django - 我如何访问 Serializer Django Rest Framework 中的 QueryString 值

python - 如何以与数据库一致的方式计算应用程序的Python端点之间的距离

python - Django Rest 框架序列化程序关系 : How to get a list of only the latest track?