Klapperstorch
Klapperstorch

Reputation: 69

React.js JWT Socket.io Authentication

I am trying to use Socket.io in React with an Express Backend, which using JWT (Passport JWT). In my usual routes I have no problems with my Auth. The Authorization header is sent (Authorization Bearer Token) and checked on the backend, however I simply do not get how to include the Bearer Token when sending data from React Client.

I have looked up the extraHeaders option but simply could not get them to work.

Here is my Code:

class Chat extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      username: "",
      message: "",
      messages: []
    };


    this.socket = io("localhost:5000", {
      extraHeaders: {
        Authorization: "My Bearer authorization_token_here"
      }
    });

    this.socket.on("RECEIVE_MESSAGE", function(data) {
      addMessage(data);
    });

    const addMessage = data => {
      console.log(data);
      this.setState({ messages: [...this.state.messages, data] });
      console.log(this.state.messages);
    };

    this.sendMessage = ev => {
      ev.preventDefault();
      this.socket.emit("SEND_MESSAGE", {
        author: this.state.username,
        message: this.state.message
      });
      this.setState({ message: "" });
    };
  }
  render() {jsx code here}

The socket connection is set up, however I have no idea how to get the token to the server. Ideally I'd send a ID in the token, decode it on the server and lookup more info about the user in my DB.

Happy Holidays and I'm thankfull for any help or hints how to solve my problem.

Upvotes: 4

Views: 4797

Answers (1)

Vikas Kumar
Vikas Kumar

Reputation: 2998

As per, the documentation extraHeaders will only work in browsers if transport option is set to polling.

so enable polling on serverside and use the following snippet

io({ 
  transportOptions: {
    polling: {
      extraHeaders: {  "Authorization": "My Bearer authorization_token_here" }
    },
  }
});

Upvotes: 1

Related Questions