The signature provided by the pusher is invalid: The expected HMAC SHA256 in hexadecimal digest is

The HTML file contains JavaScript code that calls the server for authentication. The code snippet from the HTML file is as follows:

<html>
<script>
<head>
    var options = { authEndpoint: "api/pusher.json?socket_id=9900&channel_name=presence-channel" }
    var pusher = new Pusher('98384343434343434', options);
    pusher.connection.bind('connected', function() {
        console.log("connected");
        socketId = pusher.connection.socket_id;
        console.log("socketId" + socketId);
    });

    var channel = pusher.subscribe('presence-channel');
</script>
</head>
<body></body>
</html>

The corresponding server-side code is shown below:

import com.pusher.rest.Pusher;
import com.pusher.rest.data.PresenceUser;
import com.webapp.actions.BusinessApiAction;


@Path("/api/pusher")
public class PusherAction extends BusinessApiAction {
    @POST

    @Produces({ "application/Json", "application/xml" })
    public Response pusher(@Context ServletContext context, @Context HttpServletRequest req, @Context HttpServletResponse res, @FormParam("socket_id") String socketId, @FormParam("channel_name") String channelName) throws Exception {
        System.out.println("\n\n===channel==> " + channelName + "\t socket id-->" + socketId);

        Pusher pusher = new Pusher("92063", "3055e2b132174078348c", "52cfe6c7ecb8420ad981");
        String userId = "5433d5da97d88628ec000300";
        Map<String, String> userInfo = new HashMap<>();
        userInfo.put("name", "Phil Leggetter");

        String authBody = pusher.authenticate(socketId, channelName, new PresenceUser(userId, userInfo));
        JSONObject j = new JSONObject(authBody);
        System.out.println("\n\n===authBody==> " + j.getString("auth"));
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> channelData = new HashMap<>();
        map.put("auth", j.getString("auth"));
        JSONObject ch = new JSONObject(j.getString("channel_data"));
        channelData.put("user_id", ch.getString("user_id"));
        channelData.put("user_info", userInfo);
        map.put("channel_data", ch.toString());

        return sendDataResponse(map);
        }

}

Although the response returned by the server is 200, there seems to be an error with Pusher. The error message logged by Pusher indicates an issue with the signature:

Pusher : Event sent : {"event":"pusher:subscribe","data":{"auth":"3055e2b132174078348c:980bf9a6d3a61d280d181785ccacd0e5e7999776085403f2d9bfe688842b8fe7","channel_data":"{\"user_info\":{\"name\":\"Phil Leggetter\"},\"user_id\":\"5433d5da97d88628ec000300\"}","channel":"presence-user2"}}

Pusher : Event recd : {"event":"pusher:error","data":{"code":null,"message":"Invalid signature: Expected HMAC SHA256 hex digest of 41797.10543542:presence-user2:{\"user_info\":{\"name\":\"Phil Leggetter\"},\"user_id\":\"5433d5da97d88628ec000300\"}, but got 980bf9a6d3a61d280d181785ccacd0e5e7999776085403f2d9bfe688842b8fe7"}}

Pusher : Error : {"type":"WebSocketError","error":{"type":"PusherError","data":{"code":null,"message":"Invalid signature: Expected HMAC SHA256 hex digest of 41797.10543542:presence-user2:{\"user_info\":{\"name\":\"Phil Leggetter\"},\"user_id\":\"5433d5da97d88628ec000300\"}, but got 980bf9a6d3a61d280d181785ccacd0e5e7999776085403f2d9bfe688842b8fe7"}}}

Answer №1

Ensure that the authBody returned by pusher.authenticate contains all necessary information to respond to the client request. Make sure that the response body in JSON format should include authBody when using the sendDataResponse method.

I have modified the provided example by eliminating unnecessary lines:

@Path("/api/pusher")
public class PusherAction extends BusinessApiAction {
    @POST

    @Produces({ "application/Json", "application/xml" })
    public Response pusher(@Context ServletContext context, @Context HttpServletRequest req, @Context HttpServletResponse res, @FormParam("socket_id") String socketId, @FormParam("channel_name") String channelName) throws Exception {
        System.out.println("\n\n===channel==> " + channelName + "\t socket id-->" + socketId);

        Pusher pusher = new Pusher(APP_ID, APP_KEY, APP_SECRET);
        String userId = "5433d5da97d88628ec000300";
        Map<String, String> userInfo = new HashMap<>();
        userInfo.put("name", "Phil Leggetter");

        String authBody = pusher.authenticate(socketId, channelName, new PresenceUser(userId, userInfo));

        return sendDataResponse(authBody);
    }

}

The pusher-rest-java library's README indicates that the extra functionality found previously is not needed: https://github.com/pusher/pusher-rest-java#authenticating-presence-channels

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

What is the process for implementing a filter to retrieve specific information from the data.gov.in API?

I am currently working on accessing air traffic data for my region using the data.gov.in API. Here is the link to the API I am utilizing. I am interested in learning how to implement a filter to acquire specific city data, such as Noida. ...

Modify the CSS when CKEditor is in focus

Implementing CKEditor in a symfony project using the FOS\CKEditor-bundle 1.2. I want to style the entire element containing CKEditor with a border when it is focused, similar to how questions are written or answered on Stackoverflow. By referencing a ...

Ways to remove items from Vuex store by utilizing a dynamic path as payload for a mutation

I am looking to implement a mutation in Vuex that dynamically updates the state by specifying a path to the object from which I want to remove an element, along with the key of the element. Triggering the action deleteOption(path, key) { this.$store.d ...

Exploring the process of retrieving data from localStorage in Next.js 13

Having recently delved into the realm of Next JS, I've encountered a hurdle when it comes to creating middleware within Next. My aim is to retrieve data from local storage, but I keep hitting roadblocks. middleware.ts import { key, timeEncryptKey, to ...

Retrieve a JSON object from a JSON array using a specific key

I am facing a situation where I have a json array containing multiple json objects. Let's take the example of a course object with the following structure: {"name": "Math", "unit": "3"} The json array looks something like this: [{"name": "Math", "u ...

Two separate tables displaying unique AJAX JSON response datasets

As a beginner in javascript, I am facing a challenge. I want to fetch JSON responses from 2 separate AJAX requests and create 2 different tables. Currently, I have successfully achieved this for one JSON response and table. In my HTML, I have the followi ...

Tips for effectively managing loading state within redux toolkit crud operations

Seeking guidance on efficiently managing the loading state in redux-toolkit. Within my slice, I have functionalities to create a post, delete a post, and fetch all posts. It appears that each operation requires handling a loading state. For instance, disp ...

The ng-controller directive fails to function on the content of Kendo tabstrip tabs

My ng-controller is not functioning properly for the kendo tabstrip tab content. Could you please review my code below? <!--tabstripCtrl.js--> angular.module('tabstripApp',[]); var app = angular.module('tabstripApp'); app.con ...

retrieve the result following an ajax request

In my project using spring-mvc, I have an ajax call that returns void as it only updates database data. However, if the user is not logged in, I want to redirect them to a login page. The issue is that for redirection, I need to specify String as return ...

submitting URL from dropdown menu without using the 'submit' button

My situation involves a dropdown list: @Html.DropDownList("InnerId", Model.GroupDropDownList, new { @class = "select_change" }) I am looking to achieve submitting the value when a user clicks on the selection without needing to select and then use a subm ...

Selection Change Event for Dropdown Menu

Just starting to learn JavaScript and currently working with 3 select elements on a JSP page: <select id="railwayServiceList" name="railwayService_id" onchange="changeCompaniesCombo()"></select> <select id="companyList" name="company_i ...

Issue with combining overflow-x, Firefox, and JavaScript

In Firefox, an issue arises that does not occur in other browsers. To see the problem in action, please visit this example page: -removed- Try selecting a page other than the home page. The window will scroll to your selection. You can then scroll down u ...

Identify numbers and words within a sentence and store them in an array

Looking to split a string into an array based on type, extracting numbers and floats. The current code is able to extract some values but not complete. var arr = "this is a string 5.86 x10‘9/l 1.90 7.00" .match(/\d+\.\d+|\d+&bsol ...

Exploring the World of React JS by Diving into Backend Data

Let's consider an application that consists of three pages: "HomePage" "PrivatePage" "UserManagementPage" In addition, there is a file called "BackendCommunication.js" responsible for handling communication with the backend. "Homepage.js" import Re ...

Is there a way to incorporate the information from PHP files into the output produced by JavaScript?

I am currently working on a JavaScript script that scrapes data and displays the result on the screen successfully. However, I now face a challenge in wrapping this output with pre and post content from PHP files for formatting purposes. Here is an overvi ...

Tips for ensuring a controller function only runs once in AngularJS

I have a controller that is being referenced in some HTML. The HTML changes on certain events, causing the controller function code to execute multiple times. The issue lies in a portion of the code that should only be executed once. Shown below is the ...

Determine the frequency of a specific key in an array of objects

original array: ................ [ { from: {_id: "60dd7c7950d9e01088e438e0"} }, { from: {_id: "60dd7c7950d9e01088e438e0"} }, { from: {_id: "60dd7e19e6b26621247a35cd"} } ] A new array is created to count the instances of each ...

Contrasting the use of jQuery versus AJAX for updating static page text

While I haven't fully grasped the concept of AJAX yet, my understanding is that it can be beneficial for updating specific parts of a webpage. Does using AJAX only make sense when you require server interaction? I am looking to replace text on a webp ...

Guide on transferring numerous files (50k+) from a folder to AWS S3 using node.js

Currently, my Node.js API on a Windows machine is generating numerous XML files that are later sent to an S3 bucket. The quantity of files sometimes surpasses 50k. For the uploading process, I am utilizing the aws-sdk package. Essentially, I iterate throu ...

Maximizing the potential of $urlRouterProvider.otherwise in angular js

I am encountering an issue with redirecting to the login screen when there is no UABGlobalAdminId in my storage. I have tried using $urlRouterProvider.otherwise but it doesn't seem to be functioning properly. When I attempt to debug, the console does ...