间歇性地未定义授权令牌

时间:2018-06-21 16:27:35

标签: node.js reactjs authorization token

有一个间歇性问题,我的授权令牌未定义,但是我不知道为什么,因为据我所知它是已定义的。

这是我的登录功能,在reactjs中,restAPI是axios-service。下面的代码对我使用Chrome确实有效,但是当我在与完全相同的用户的私有窗口中使用Firefox时,由于未定义我的令牌,因此从服务器返回了401。我无法在Chrome中重现此行为,但其他用户可以,并且发现可以在FF私有模式下重现此行为以进行测试。

 async onSuccessLogin(payload, formProps) {
    const { token, user } = payload.data;
    await cookie.save('token', token.accessToken, { path: '/' });
    await cookie.save('user', user, { path: '/' });
    restAPI.get('/api/customers/profiles/me', user.id).then(res => {
      if(!res  || res.userName == null || res.phoneNumber == null || res.email == null || res.age == null || res.birthday == null || res.state == null || res.city == null){
        window.location.href = CLIENT_URL + '/#/profile';
      } else {

      if((res.userName.length < 2) || (res.phoneNumber.length < 2) || (res.email.length < 2) || (res.age.length < 2) || (res.birthday.length < 2) || (res.state.length < 2) || (res.city.length < 2) || (res.asset.length < 2) || (res.role.length < 2)){
        window.location.href = CLIENT_URL + '/#/profile';
      } else {
        window.location.href = CLIENT_URL;
      }
      }
    })

此Node.js代码返回了间歇性401,该代码在调用之前被调用以从上方获取用户个人资料:

const authorization = async (req, res, next, role) => {
  let token;
  if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {   // <--token undefined here intermittent
    token = req.headers.authorization.split(' ')[1];
  } else if (req.query && req.query.token) {
    token = req.query.token;
  } else return res.sendStatus(401);

  try {
    const userId = jwt.decode(token, config.jwtSecret).sub;
    const userList = req.app.get('container').get('user.list');
    const user = await userList.findOne({
      id: userId
    });

    if (!user) return res.sendStatus(401);

    req.user = user;

    return next();

  } catch (e) {
    return res.json(e.message).status(401);
  }

};

我发现在FF中,如果出现401错误,然后在浏览器中点击重新加载,我现在就可以获取数据了。

0 个答案:

没有答案
相关问题