Guide to transferring headers when redirecting to a different route using hapijs

obtainAuthToken(request, response) {
     let token = //generate JWT token here
     request.headers.Authorization = token;
     //also attempted
     request.response.header('token' , token);
     response.redirect('/differentRoute')
    }

The different route does not seem to retain these headers. I also experimented with setting the token in the 'onPreResponse' stage but encountered similar outcomes. I am working with hapi version 16.

Answer №1

After including it as a search parameter in the redirect URL, I ensured that these parameters are not transmitted to the server when making a request. This way, the token will not be stored in any logs.

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

Answer №2

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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript time to stop typing issues

Here's a functional JSfiddle I created for this question: http://jsfiddle.net/KSCLC/ I'm working on a simple page where you can either scan or manually type in a UPC, which then automatically gets added to a table for display. I came up with som ...

Ways to retrieve the currently selected id from the router within the next 14 steps

I'm currently trying to extract the ID that is selected (#about, #home, #blog) or the full path (http://localhost:3000/#about, http://localhost:3000/#home) from the router. I am working with Next.js version 14.0.3 This is my approach: My current URL ...

Error: The value of 'filesLeft[file.fieldname]' is not defined in multer

Recently, I've been delving into the world of multer and attempting to upload a file to an express server using multer. On the client side, I'm working with ReactJS: Here are the versions I am using: express - 4.15.2 multer - 1.3.0 ...

Sending files through ajax with php

Hey there! I've been working on uploading files using Ajax and PHP, following a tutorial. Here's the code I have so far: upload.js: var handleUpload = function (event){ event.preventDefault(); event.stopPropagation(); var fileInput= document.ge ...

Mastering Error Management with NodeJS and Express

I have a simple migration code that handles dropping, creating, and seeding a table in my database. this.knex.schema.dropTable(this.tableName) .catch((err) => console.log(err)) .then(() => { this.knex.schema.createTable(this.tableName, function( ...

What is the status of --async-stack-traces feature in node version 16 and above, and is there a replacement option available?

My query is similar to this one, but pertains to Node 16+. The response at the bottom of that thread mentions: For Node 14+ you can utilize the --async-stack-traces flag to enhance stack trace when dealing with asynchronous code. However, there are certain ...

Issue with specific MongoDB pipeline causing change stream not to trigger

I'm currently tackling a project that requires monitoring MongoDB documents for groups managed by a user. To achieve this, I have implemented change streams in MongoDB. However, I've encountered an issue where the change stream fails to trigger w ...

Is it possible to make SVG Text editable within Angular?

Since version 1.3.1, AngularJS has improved significantly when it comes to writing SVGs. Typically, the interaction involves data being retrieved from a database or form and Angular then populating the nodes in the SVG. However, I am now looking to bypas ...

Switching to fullscreen mode and eliminating any applied styles

I'm trying to enable fullscreen mode with a button click. I've added some custom styles when the window enters fullscreen, however, the styles remain even after exiting fullscreen using the escape key. The styles only get removed if I press the e ...

Problem with deleting or substituting symbols and character codes within a String

I am attempting to send an object called dataO from Node.js/Express/EJS to the client side. On the Node.js script side: var dataO = {"first":[20000, 14000, 12000, 15000, 18000, 19000, 22000], "second":[12000, 11000, 18000, 12000, 19000, 14000, 26000]}; var ...

Loading data in a Bootstrap datatable can sometimes be a slow process

Hi there, I'm currently using a codeigniter bootstrap theme datatable to retrieve data from my database. However, the loading time is quite slow as it loads all the data at once before converting it into pagination. Is there any way to only load 10 re ...

Getting the chosen option from a dropdown list mapped in ReactJS

I am working on a dropdown select option that is linked to the data of an array object called 'template_titles'. Currently, the value in the dropdown corresponds to the title in the object. My goal is to be able to extract and use the selected va ...

Issue with Vue.js Typescript when setting a debounced function

Upon debouncing a function in my Vue.js application, I encountered the following error message: Type 'DebouncedFunc<(queryParams: QueryParams, page?: number) => Promise<void>>' is not assignable to type '(queryParams: QueryPa ...

Challenges encountered when attempting to download a file using jQuery's GET method

I am working with an API Server that responds to requests in the following format: http://localhost:8080/slim3/public/api/v1/files/Test1.jpg http://localhost:8080/slim3/public/api/v1/files/Test2.txt ... When I enter such a URL into my browser, I receive ...

Remove all keys of type BaseType from objects that are children of BaseType

There are two types: BaseType and BabyType. export type BaseType = { id: string } export type BabyType = BaseType & { name: string }; In a generic layer where <T extends BaseType> is used, the item being dealt with is actually a 'B ...

JavaScript - Swapping out element in object array

I'm struggling to develop a function that can normalize features within a dataset, ensuring they fall between 0 and 1. My goal is to iterate through all the features and update their values as I perform normalization. While the normalization process i ...

Dealing with errors in Mongoose within a Node.js application: A guide

I'm currently working on a node.js application using express, mongoDb, and mongoose. While the app is able to save users without any issues, I am facing an error in the code snippet below. The console always displays an error message even when the use ...

If a checkbox is checked, then the value in the textbox should be multiplied by 0

I'm faced with a challenge involving a non-clickable textbox that is meant to hold a running total. Each time a checkbox is clicked, its value should be added to the total in the textbox. However, I am now struggling to figure out how to perform mult ...

Converting Dates to getTime() in AngularJS prior to server transmission

In my form, I am using <input type="datetime-local" ng-bind="course.endDate".. to set a model variable. Before sending the date to the server, I need to convert the date 2015-04-04T22:00:00.000Z to an integer using getTime(). In the controller, I added ...

Simply input the data into the fields of the weekly tds

I am facing an issue with my code where, upon clicking the "apply to all" button, it automatically populates the columns for Monday through Friday only. However, I need Saturday and Sunday to remain empty without any data. $('#elemento').click ...