Django rest-auth 令牌认证

pet*_*176 2 django django-rest-framework reactjs 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));
      })
  }
}
Run Code Online (Sandbox Code Playgroud)

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

REST_FRAMEWORK = {
   'DEFAULT_AUTHENTICATION_CLASSES': [
       'rest_framework.authentication.TokenAuthentication',
   ],
} 
Run Code Online (Sandbox Code Playgroud)

然后我收到未经授权的错误代码 401。任何人都可以指导我朝着正确的方向前进吗?谢谢!

gro*_*boy 5

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

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