I came across a clever solution utilizing cookies that I wanted to share with you:
I specifically refer to the jwt header issue mentioned earlier, but this approach can be applied to any header and page transition scenario, even when switching to another website.
Firstly, generate the token - typically after a successful login - and store it in a cookie within the browser:
// 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);
Next, in an onPreAuth event, extract the token from the cookie and place it in a 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') {
// Redirect to /login if authentication is essential but missing
return h.redirect('/login').takeover();
}
// This header will be utilized by the jwt authentication mechanism.
req.headers.authorization =
pfx + ' '+t_data;
}
catch(err) {
console.log(err);
}
return h.continue;
}
}
];
By following this method, the new token is automatically saved in the browser's cookie for secure storage and retrieval on subsequent requests, while also being loaded into the request header for each new browser request.