Thursday, March 9, 2017

socketio-jwt: Connected to SocketIO, Authenticating

I've followed multiple tutorials to set up socketio-jwt, but every time it seems that I'm not getting past this part:

Connected to SocketIO, Authenticating

Any ideas?

Client side:

<h1>Socket Connection Status: <span id="connection"></span></h1>

<script type="text/javascript">
    $(document).ready(function () {
        socketIOConnectionUpdate('Requesting JWT Token from Laravel');

        $.ajax({
            url: 'http://localhost:8000/token?id=1'
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
            socketIOConnectionUpdate('Something is wrong on ajax: ' + textStatus);
        })
        .done(function (result, textStatus, jqXHR) {

            socketIOConnectionUpdate('Connected to SocketIO, Authenticating')
            /* 
            make connection with localhost 3000
            */
            var token = result.token;
            var socket = io.connect('http://localhost:3000');
            socket.on('connect', function () {
              socket
                .emit('authenticate', {token: token}) //send the jwt
                .on('authenticated', function () {
                  console.log('authenticated');
                  socketIOConnectionUpdate('Authenticated');
                })
                .on('unauthorized', function(msg) {
                  socketIOConnectionUpdate('Unauthorized, error msg: ' + msg.message);
                  throw new Error(msg.data.type);
                })
            });
        });
    });

    /* 
    Function for print connection message
    */
    function socketIOConnectionUpdate(str) {
        $('#connection').html(str);
    }

Server side

var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var socketioJwt = require('socketio-jwt');
var dotenv = require('dotenv').config({path:'../.env'});

var port = 3000;

io
    .on('connection', socketioJwt.authorize({
        secret: dotenv.JWT_SECRET,
        timeout: 100 // 15 seconds to send the authentication message
    }))
    .on('authenticated', function(socket){
        console.log('connected & authenticated: ' + JSON.stringify(socket.decoded_token));
        socket.on('chat message', function(msg){
            debugger;
            io.emit('chat message', msg);
        });
    });

http.listen(port, function(){
  console.log('listening on *:' + port);
});



via Z0q

Advertisement