Moshe Shmukler
Moshe Shmukler

Reputation: 1300

Auth0 and Socket.IO - correct implementation

I am working on securing socket.io services with Auth0 authentication. On the server, I did the below:

app.configure(feathers.socketio(function(io) {
  if(process.env.JWT_AUTH == 'disable' && app.get('env') !== 'production') {
    console.log('*** JWT_AUTH disabled: Free passes today ***');
  } else {
    io.use(socketioJwt.authorize({
      secret: new Buffer(process.env.AUTH0_CLIENT_SECRET, 'base64'),
      audience: process.env.AUTH0_CLIENT_ID,
      handshake: true
    }));
  }
  io.on('connection', function(socket) {
    socket.emit('news', { hello: 'world' });
    socket.on('my other event', function (data) {
      console.log(data);
    });
  });
}));

In order to pass a token with socket.io from the client, I do:

var io = require('socket.io-client');
var TOKEN_EXPIRATION_IN_SECONDS = 3600;

var createToken = require('auth0-api-tokens')({
  clientId: 'process.env.AUTH0_CLIENT_ID',
  clientSecret: new Buffer(process.env.AUTH0_CLIENT_SECRET, 'base64'),
})

// each key is an entity, each array element is an action
var token = createToken({
  scopes: {
    users: ['read', 'update'],
    clients: ['delete']
  },
  lifetimeInSeconds: TOKEN_EXPIRATION_IN_SECONDS
});

console.log("Auth0 token: ", token);

var socket = io.connect('http://127.0.0.1:8000', {
  'query': 'token=' + token});
var app = feathers().configure(feathers.socketio(socket));

I am not utilizing token scopes, but I copied them from an example. Should probably not be the problem.

When I turn-on JWT_AUTH, server stops servicing unauthorized [as well as authorized] socket.io requests. Without it, my REST API are protected, but socket.io is not. I need socket.io protected with Auth0. What can I check?

Thank you

Upvotes: 0

Views: 1950

Answers (2)

Moshe Shmukler
Moshe Shmukler

Reputation: 1300

For me the below worked:

io.use(socketioJwt.authorize({
  secret: new Buffer(process.env.AUTH0_CLIENT_SECRET, 'base64'),
  handshake: true
}));

secret and handshake without audience.

Upvotes: 0

Kassandra Perch
Kassandra Perch

Reputation: 580

var createToken = require('auth0-api-tokens')({
    clientId: 'process.env.AUTH0_CLIENT_ID',
    clientSecret: new Buffer(process.env.AUTH0_CLIENT_SECRET, 'base64'),
})

Since this is running on the client (as your question suggests), make sure you have re-created the process.env object on the client so it can access it, and find your environmental variables.

Upvotes: 1

Related Questions