hapijs - 如何在重定向到另一条路线时传递 headers

hapijs - how to pass headers while redirecting to another route

generateToken(request, reply) {
     let token = //JWT token generated 
     request.headers.Authorization = token;
     //also tried
     request.response.header('token' , token);
     reply.redirect('/newPath')
    }

新路径没有这些headers。我还尝试从 'onPreResponse' 阶段设置令牌,但结果相同。 我正在使用 hapi 版本 16。

将其作为搜索参数添加到重定向 URL。请求 URL 时不会将搜索参数发送到服务器,因此令牌不应出现在任何日志中。

res.redirect(`http://appServer:5001/?key=value#jwt=${token}`)
const token = (new URL(document.location)).searchParams.get('jwt');

我发现了一个使用 cookie 的非常优雅的解决方案: 我说的是您正在谈论的相同 jwt header,但通常应该适用于任何 header 和任何页面切换,即使在访问其他网站之后也是如此。

生成令牌,大概在成功登录时,将其保存到 cookie 中以保存在浏览器中:

// generate a jwt token
let token = Jwt.token.generate('your_id', {
    key: jwtKey,
    algorithm: 'HS256'
}, {ttlSec: 24*60*60});
// save the token in a cookie
const response = h.response();
response.state("jwt_token", token, cookie_options);

现在,在 onPreAuth 事件中,将令牌从 cookie 读取到 header:

module.exports = [
  {
    type: 'onPreAuth',
    method: (req, h) => {
      try {
        var pfx = your_jwt_strategy.httpAuthScheme;
        const server = req.server;
        const auth = server.auth;
        const config = auth.lookup(req.route);
        var t_data = req.state.jwt_token;
        if (!t_data && config.mode == 'required') {
          // if authentication is required and 
          // missing, will redirect to /login
          return h.redirect('/login').takeover();
        }
        // this header will be read by the
        // jwt authentication mechanism.
        req.headers.authorization = 
          pfx + ' '+t_data;
      }
      catch(err) {
        console.log(err);
      }
      return h.continue;
    }
  }
];

此串联将自动将新令牌保存在浏览器 cookie 中,从而确保其安全保存并在每次请求时重新加载,并在新的浏览器请求时将其重新加载到请求 header 中。