Search code examples
node.jsreactjspassport.jspassport.socketio

Passport Socket.io Authentication With Redirect


I'm using Passport.Socket.io to access user's login information inside socket.io, however, I cannot figure out a way to handle authentication for each and every page.

1) My goal is to check if a user is logged in, if they are not, I would like to redirect them to the login page. I know that Passport.Socket.io has a function for handling authentication failure but how can I implement redirect inside this function. Is there a better way to handle this? I do not want to call redirect inside each and every client side page.
2) I would like to know what is the best way to call passport authenticate. Do I have to redirect users to the server port and handle it with express? or is there a better way?
NOTE: My client side code runs on Nginx and is on a separate port.

io.use(
passportSocketIo.authorize({
key: "connect.sid",
secret: "secret",
store: new MySQLStore(options),
passport: passport,
cookieParser: cookieParser,
fail: onAuthorizeFail,
})
);

function onAuthorizeFail(data, message, error, accept) {
  // redirect in here? 
}

UPDATE:
This is what I have right now. Is this correct way of doing this, or is there a better way? I still haven't found a better solution for my 2nd question.

function onAuthorizeFail(data, message, error, accept) {
  accept(new Error("Auth Error"));
}

and on client side:

  initSocket = () => {
const socket = io(socketURL);
socket.on("connect", () => {
  console.log("Socket online");
});
socket.on("error", () => {
  window.open("http://localhost:3000/login", "_self");
});
this.setState({ socket });
};

Solution

  • I solved my problem by using Redux and handling redirect inside BrowserRouter:
    1. Implement a shared state for authentication.
    2. Wrap protected pages in a special authentication component that handles redirect. This is explained in React-Router documentation available here