What is the best way to arrange the keys within a nested object in JavaScript?

Question:

{ "foo": "bar", "bar": "baz", "baz" : { "nestedKey": "foo" } }

In order to sign this request using the Hmac512 algorithm, I must first stringify the object.

I am concerned that if the key order is not preserved, the generated signature on the server and client side may differ.

To address this concern, my solution is to alphabetically sort the keys of the object (including nested keys).

How can I implement this sorting process?

Answer №1

The original post emphasizes the importance of having a deterministic input for the HMAC process.

It is worth noting that in JavaScript, the order of object elements cannot be controlled, despite our best efforts to do so. This issue tends to surface periodically.

The solution is to sort the stringified version of the string itself before passing it into the HMAC method.

You can explore using json-stable-stringify as a tool to address this challenge.

Simply provide the resulting sorted string as input to the HMAC method without requiring base64 encoding.

Answer №2

It is important to make sure that the message is consistent on both ends without any alterations or adjustments needed.

In essence, follow this algorithm:

 base64(sign(utf8(json message)))

On the Client Side:

  1. Stringify: Convert the JavaScript object into a string

  2. UTF-8: Use a standardized encoding such as UTF-8

  3. Sign: Compute HMAC over the resulting message

  4. base64: Change the binary signature to base64 format

Send the JSON message and the signature to the client

On the Server Side:

Receive the original message from the client and execute steps 2-4. Verify if the signatures match

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

Guide on using JavaScript to automatically scroll a HTML page to the top on any mobile browser

Can JavaScript be utilized to smoothly scroll an HTML page to the top? I am looking to achieve this with a stylish animation that functions correctly on all mobile browsers. jQuery is the library I am using on this particular page. Thank you, ...

Clicking on the input triggers the appearance of a border using the OnClick function

I am currently developing my own website with a login feature that requires input tags of text-type. I would like to implement a functionality where clicking on these input tags will display a border, even when the mouse is not directly hovering over them. ...

Using JavaScript variables within an @if statement in Laravel within the innerHTML segment

How can I incorporate a JavaScript variable 'x' into an @if statement in Laravel? I have tried placing it both inside and outside of the @if statement. When placed outside, it works perfectly fine, but I really need to perform an action based on ...

Navigating the world of updating problems with Express.js

Currently, I am working on a MEAN stack project and facing challenges with the routing for updating. Saving operations are functioning correctly. In my Angular controller, I have defined the following scope method in which staff represents the object subm ...

Monitoring data updates within an Angular directive

Is there a way to activate a $watch variable in an Angular directive when modifying the data within it (eg. adding or removing data), without assigning a completely new object to that variable? Currently, I am loading a basic dataset from a JSON file usin ...

How to format numbers with commas in AngularJS to make them easier to read

One of my variables looks like this: $scope.numbers = 1234567. When I apply the filter {{numbers| number : 0}}, the result is 1,234,567. Is it possible to get a result like 12,34,567 instead? Thank you in advance. ...

Tips on creating a subsequent post for a file that has been uploaded to a Node Express server and then forwarded to a different API

We are currently working with an Express server in Node, where we upload a file on one route and then need to send this file to another endpoint for processing. However, the file is not stored locally on the server; it exists as an uploaded object. I&apos ...

Problem with session cookies not being included in cross-origin replies using Express, Redis, and Next.js

I am currently working on a project that involves using an Express.js backend in conjunction with a Next.js frontend. The backend utilizes the Redis and connect-redis packages for session management, while the server is deployed on Heroku with the Heroku-D ...

What is the best way to add a separator in a b-dropdown menu once the options have been loaded using Vue?

Here is the code snippet for my dropdown element: <b-dropdown id="SchemaDropdown" name="SchemaDropdown" variant="form-control" class="" style="width: 100%" ...

Determine the row index by identifying the row id and table id

I need to retrieve the Index number of a row when a hyperlink is clicked, while also passing additional data from this tag. <a href="javascript:void(0);" onclick="EditDoctorRow(' + RowCountDoctorVisit + ');"> <i class="fa fa-edit"&g ...

Error code "ER_BAD_FIELD_ERROR" was encountered with errno 1054 and sqlState "42S22" in index 0 while using MySQL with Angular and managing sessions

When I log in, the following code is executed: <div ng-include="'partials/navbar'"></div> <form name="form" ng-submit="login(form)"> <div> <input type="text" placeholder="Email" ...

Crop and upload images asynchronously using Node.js

I need to resize an image into multiple sizes and then upload them to AWS S3. The specific resizing dimensions are stored in an array. To accomplish this, I am utilizing the async waterfall method along with the series method. async.each(crop_sizes, func ...

Incorporating a YouTube channel into mobile websites

While it's relatively easy to embed single YouTube videos in mobile pages with the help of Google, I'm still struggling with embedding a whole channel. The issue seems to revolve around the screen width, and my attempts at using JavaScript have n ...

Every time I check Req.body, it always comes back empty, even after I've already entered information in my form

I am facing an issue with my form where I am trying to input a comment for my shoe and then send it to my node.js server through a POST request. However, the req.body.comment is consistently returning an empty string even when the form is filled out. In m ...

Is there a way to send JSON using ExpressJS in UTF-8 encoding?

Currently facing an issue with my new web app that I haven't encountered in the past. Experimenting with a simple code snippet like this: var jsonToSend = {hello: "woørld"}; app.get('/someUrl', function(req, res) { res.setHeader('Co ...

Tips for sending Json data through a form to a controller and storing it in a database

I am working on a form that contains a sample table with values. The table (id=sampleTbl) has two columns: name and age. My goal is to save this data into my database table named person (id=AI, name, age) when the submitButton (id=idOfButton) is clicked. ...

When employing useEffect, clearInterval cannot halt the execution of SetInterval

My attempt to create a function that initiates a countdown when the isPlaying variable is true and stops when it's false has not been successful. Instead of working as intended, it starts multiple intervals concurrently. The value of isPlaying changes ...

Is it possible to avoid passing each individual Vue prop by destructuring them?

Essentially, I am working with a component <Device> v-for="device in devices" :key="device.name" :device="device" :name="device.name" :number="device.number" :type="device.type" :status=&qu ...

Javascript Callback function not working as expected

I'm attempting to include an anonymous callback function in my code. I know it might seem a bit messy. By typing into the intro section, it triggers the animation using the .typed method with specific parameters. What I'm struggling to do is imp ...

The code for implementing the "Read More" feature is not functioning as intended

I have been experiencing an issue with the implementation of the "read more" feature on my website. Although the code seems to be functioning properly, it only works after pressing the read more button twice. This particular code is designed to detect the ...