authenticationwebrtcpeerjs

How can I authenticate PeerJS connections to the PeerServer?


I am currently running my own PeerServer while I develop an application. I am wondering how I can authenticate each individual ID so that when someone connects, then have to have the right API key (unique to their name).

Could I set up a service where, when they register, a new key is generated and peerjs will recognize it?


Solution

  • You can send a token in the options, for example a JWT with the userId encoded:

    const myPeer = new Peer(userId, {
        host: '/',
        token: userJwt
    })
    

    Receive it when the user connects and validate it. If the ids don't match, close the socket:

    peerServer.on('connection', (client) => { 
        const decodedToken = decodeToken(client.token)
        if (!decodedToken || decodedToken.userId !== client.id)
            client.socket.close()
    })