socket.io authentication after socket established - authentication

I'm working on a small multiplayer game. I'd like to introduce authentication. I'm using Node.js and Socket.io.
When the user arrives that the main page - I want them to join the game whether they are logged in or not - but they will be unable to do anything within it (only watch).
How could I then go about authenticating the user on the already open socket?
Could I maintain the authentication still if they left the site and came back? Can you pass a cookie through a web socket?
EDIT
To further my question. One of the possible thoughts I've had is to provide the websocket connection, then when they try to login in, it passes username and password as a message to the websocket.
client.on('onLogin', loginfunction);
I could then take the username and password, check against the database, then take the session ID of the socket and pass it somewhere to say that session is authenticated to that user.
Is this secure? Could I still implement a cookie on the socket so they could come back? Is there any way within socket.io of stating that the socket is now authenticated instead of manually checking on each message received?
Cheers

This isn't actually too hard, but you're approaching it the wrong way. A couple things:
You cannot set a cookie with socket.io; you can, however, get the cookie values of any connected client at any time. In order to set a cookie, you will have to send a new http response, meaning the user must first send a new http request (aka refresh or go to a new page, which it sounds is not a possibility for you here).
Yes: socket.io is secure (to the extent that any transmitted data can be).
As such, you can do the following:
On the user's initial connection, create a cookie with a unique session ID, such as those generated from Express's session middleware. You will need to configure these not to expire on session end though (otherwise it will expire as soon as they close their browser).
Next you should create an object to store the cookie session IDs. Each time a new connect.sid cookie is set, store in your new object with a default value of false (meaning that the user has been authenticated by session, but not by logon)
On the user's login, send a socket emit to the server, where you can then authenticate the login credentials, and subsequently update the session id object you created to read true (logged in) for the current socket id.
Now, when receiving a new http request, read the cookie.sid, and check if its value in your object is true.
It should look something like the following:
var express = require('express'),
http = require('http'),
cookie = require('cookie');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
app.use(express.cookieParser());
app.use(express.session({
secret: 'secret_pw',
store: sessionStore,
cookie: {
secure: true,
expires: new Date(Date.now() + 60 * 1000), //setting cookie to not expire on session end
maxAge: 60 * 1000,
key: 'connect.sid'
}
}));
var sessionobj = {}; //This is important; it will contain your connect.sid IDs.
//io.set('authorization'...etc. here to authorize socket connection and ensure legitimacy
app.get("/*", function(req, res, next){
if(sessionobj[req.cookies['connect.sid']]){
if(sessionobj[req.cookies['connect.sid']].login == true){
//Authenticated AND Logged in
}
else{
//authenticated but not logged in
}
}
else{
//not authenticated
}
});
io.sockets.on('connection', function(socket){
sessionobj[cookie.parse(socket.handshake.headers.cookie)['connect.sid'].login = false;
sessionobj[cookie.parse(socket.handshake.headers.cookie)['connect.sid'].socketid = socket.id;
socket.on('login', function(data){
//DB Call, where you authenticate login
//on callback (if login is successful):
sessionobj[cookie.parse(socket.handshake.headers.cookie)['connect.sid']] = true;
});
socket.on('disconnect', function(data){
//any cleanup actions you may want
});
});

Chris, I'm won't be able to answer since I'm not an expert on socket.io, but I can maybe try to point you in another direction that can help you - and take away some development time.
But first, a disclaimer: I work for Realtime.co and am not trying to do any sort of advertising. I work closely with developers and I'm just trying to help you by providing you an out-of-the-box solution for your problem. Also, being a gamer, I can't stay away from trying to help people getting their games out there!
Realtime uses an authentication/authorization layer in which you can provide user read/write permissions to channels. When users enters the website you can give them read only permissions to the game channel and once they login, you can then give them write permissions. This can be easily done by doing an authentication post and reconnecting to the server (it can all be done client side). I would do it server-side, though, to increase security.
Realtime has a Node.js API so you can easily integrate it with your server. Since it also has APIs for many other platforms (including mobile) and they all work the same way, you can actually have your game working in multiple platforms over the same communication layer, while having full control over channels.
Thanks for reading.
Edit:
You can read the documentation here for more info: http://docs.xrtml.org/

Socket.io has an option to pass extraHeaders. One can use that to pass a token from the client. The server would use the desired authentication algorithm to decrypt the token and get the user_id.
socket.js
import io from 'socket.io-client';
export const socket = io('https://remote-url');
export const socketAuth = () => {
socket.io.disconnect(); //This uses the same socket and disconnect with the server.
socket.io.opts.extraHeaders = {
'x-auth-token': JSON.parse(window.localStorage.getItem('auth-token')),
};
socket.io.opts.transportOptions = {
polling: {
extraHeaders: {
'x-auth-token': JSON.parse(window.localStorage.getItem('auth-token')),
},
},
};
socket.io.open(); //Opens up a new connection with `x-auth-token` in headers
};
client.js
import { socket, socketAuth } from 'utils/socket';
socket.on('unauthenticated-messages', () => {
someAction();
});
//After user logs in successfully
socketAuth();
socket.on('authenticated-messages', () => {
someAction();
});

Related

How to implement a login page with JSON Web Token in Ember app with express api

I added authentication for my Express API following this guide and after testing my secret-routes everything seems to work properly. Now my question is how can this be used in an Ember app login page. After receiving the secret token after a successful login how does the browser know you are signed in. How would one log out? How does the ember application know who is signed in? Is there any thing in particular security wise that I should be at tentative to while working on this?
You should use addons to handle most of the heavy lifting for you.
ember-simple-auth-token has setup directions that have you create a login route which will take a username / password and send it to your server for validation. The token response will then be available in your app until the user logs out.
The example looks like
import Controller from '#ember/controller';
import { inject } from '#ember/service';
export default Controller.extend({
session: inject('session'),
actions: {
authenticate: function() {
const credentials = this.getProperties('username', 'password');
const authenticator = 'authenticator:token'; // or 'authenticator:jwt'
this.get('session').authenticate(authenticator, credentials);
}
}
});
You also create the logout route which handles logging out of your app as well as sending any logout request to the server.
If possible you should align your server to the defaults, but you can configure nearly everything.
Authentication Options
ENV['ember-simple-auth-token'] = {
tokenDataPropertyName: 'tokenData'; // Key in session to store token data
refreshAccessTokens: true, // Enables access token refreshing
tokenExpirationInvalidateSession: true, // Enables session invalidation on token expiration
serverTokenRefreshEndpoint: '/api/token-refresh/', // Server endpoint to send refresh request
refreshTokenPropertyName: 'refresh_token', // Key in server response that contains the refresh token
tokenExpireName: 'exp', // Field containing token expiration
refreshLeeway: 0 // Amount of time to send refresh request before token expiration
};
We've been very happy with this addon in production for 3 years and I'd highly recommend it.

Retrieving & storing access_token with Passport

I'm using PassportJS along with openid-client and cookie-session in my Express server for authentication. I'm using openid-client's "Usage with Passport" as a starting point, and I'm currently able to authenticate successfully. Since I need an access token for APIs that are proxied through my server, I chose to save the access token in my user session with this bit of code:
passport.use(
'oidc',
new Strategy(
{ client, params, passReqToCallback, sessionKey, usePKCE },
(req, tokenset, userinfo, done) => {
logger.info('Retrieved tokenset & userinfo');
// Attach tokens to the stored userinfo.
userinfo.tokenset = tokenset;
return done(null, userinfo);
}
)
);
My next step is to get and store a new access token. Part of the information that comes with tokenset is the expires_at key, and it's set to expire in one hour. So of course, if it's close to expiring or has expired, I want to get a new token.
The documentation says to use:
client.refresh(refreshToken) // => Promise
.then(function (tokenSet) {
console.log('refreshed and validated tokens %j', tokenSet);
console.log('refreshed id_token claims %j', tokenSet.claims);
});
Okay, I understand that and I have that bit of code working as well. But I have no idea how to save it back into my user session. If I make a subsequent API call that's proxied through my server, I'll still have the old token in req.session.passport.user.tokenset.access_token. So how do I update that?
(I probably should put as a caveat I'm still very new to OpenID / Oauth authentication as well as Passport itself, so some of what I'm doing may be completely obvious.)

bind socket.io id to user id without sessions (express, passport JWT)

I'm developing RESTful API on express, with JWT and passport for authorization. I want to implement socket.io connection for notification and signalling purposes (WebRTC session establishing). I don't want to implement standard session management, don't want to deal with cookies, but somehow I have to be able to address particular user via socket. I have event handling in all my routes, so app is aware of auth-ed requests and corresponding user ids. One approach(probably) is to create socket io group with user id, add socket to this group and emit there. (Engaging reconnection handling and checking socket existence on every subsequent request - that's way overcomplicated). I guess there should be a better approach. I also use Redis, so I can leverage that in this scheme. Any suggestion is appreciated, thank you
Well, I managed to solve that in such a manner.
Server:
import jwt from 'jwt-simple'; //I'm using ES6/Babel
module.exports = function(app) {
var io = app.get('io'); //Import io any possible way,
//here I do it like so because I set
//app.set('io', io) in my index.js
var user_id;
io.on('connection', socket => {
// Recieve encoded token from client, decode and find user id
// To do - check againt database
socket.on('auth', token => {
if (token) {
var decoded = jwt.decode(token, 'secret')
user_id = decoded.sub
socket.emit('auth', user_id);
}
})
// Join room proposed by client - user id string
socket.on('room', room => {
socket.join(room)
console.log('Server joined room...', room)
//emit message to user id from anywhere in the app
io.sockets.in(user_id).emit('message', 'what is going on, party people?');
})
})
}
client:
var token = localStorage.getItem('token');
var socket = io();
socket.on('connect', data => {
socket.emit('auth', token);
socket.on('auth', user_id => {
socket.emit('room', user_id);
})
})
Now to address specific user I can always emit to room id equal to user id, provided that user has got credentials. Even after browser refresh.
Photo: the left client has valid token in localStorage, the right one doesn't

ember simple auth session, ember data, and passing a Authorization header

I have a working oauth2 authentication process where I get an access token (eg from facebook) using ember simple auth, send it to the back end which calls fb.me() and then uses JWT to create a token. This token is then sent back to the ember app, which then has to send it with every server request, include those requests made by ember-data.
I also need to have this token available after a browser reload.
I have tried many options, where I set a property 'authToken' on the session - I believe that this uses local storage to persist the authenticated session.
But I always seem to have trouble with coordinating the retrieval of this token - either I don't have access to the session, or the token is no longer on the session, or I can't change the ember data headers.
Does anyone have a working simple example of how this can be done - I think it should be easy, but I'm obviously missing something!
Thanks.
Update
The only thing I've been able to get working is to use torii as shown below, but the session content is still lost on refresh - I can see its still authenticated, but its lost the token I set here. So I'm still looking for a real solution.
authenticateWithGooglePlus: function () {
var self = this;
this.get('session').authenticate('simple-auth-authenticator:torii', 'google-oauth2')
.then(function () {
resolveCodeToToken(self.get('session'), self);
});
}
resolveCodeToToken gets the bearer token from the server, sets it on the session and then transitions to the protected page:
function resolveCodeToToken(session, route) {
var authCode = session.content.authorizationCode;
var type = session.content.provider.split('-')[0];
$.ajax({
url: 'http://localhost:4200/api/1/user/auth/' + type,
data: {authCode: authCode}
}).done(function (response) {
// todo handle invalid cases - where user is denied access eg user is disabled
session.set('authToken', response.token);
route.transitionTo('activity', moment().format('DDMMYYYY'));
});
}
And I have a custom authorizer for putting the token (stored in the session) on every request:
import Base from 'simple-auth/authorizers/base';
export default Base.extend({
authorize: function(jqXHR, requestOptions) {
var accessToken = this.get('session.content.authToken');
if (this.get('session.isAuthenticated') && !Ember.isEmpty(accessToken)) {
jqXHR.setRequestHeader('Authorization', accessToken);
}
}
});
I'm not sure why this.get('session.content.authToken') would be undefined after a refresh, I thought by default the session was persisted in local storage. The fact that it is authenticated is persisted, but thats useless without the token since the server will reject calls to protected endpoints.
You'd want to implement your own custom authenticator that first gets a token from Facebook and then sends that to your own server to exchange it for a token for your app. Once you have that you get authorization of ember-data requests as well as session persistence etc. for free.
Have a look at this example: https://github.com/simplabs/ember-simple-auth/blob/master/examples/7-multiple-external-providers.html

Session Property not saving in session store when retrieving from socket.io

What I am trying to accomplish is to store the username of the current user in the session, such that it can be retrieved by socket.io.
Currently, I have the client sent its sessionId to the socket.io endpoint (via io.connect):
var socket = io.connect('http://localhost?sessionId=' + sessionid);
and then on the server side, I have:
io.use(function(socket, callback) {
if (socket && socket.handshake && socket.handshake.query && socket.handshake.query.sessionId) {
var sessionId = socket.handshake.query.sessionId;
sessionStore.get(sessionId, function(error, session) {
socket.handshake.sessionId = sessionId;
if (error) {
callback('Could not set session id with socket io authorization handshake!', false);
} else if (!session) {
callback('There was no session found during socket io authorization handshake!', false);
}
console.log(session);
socket.session = session;
callback(null, true);
});
} else {
callback('No sessionId value was provided in query string to socket io connect from client', false);
}
});
This correctly retrieves the session from the client-provided sessionid (assuming the id exists, of course).
Now, what I want to do is be able to is get the passportjs-managed username accessible from within the socketio handlers, via the session.
So, to start with, I have this code in the router controller for this endpoint:
router.get('/', Authentication.redirectIfNotAuthenticated, function(req, res) {
req.session.user = req.user;
console.log(req.session);
res.locals.sessionId = req.session.id;
res.render('mypage', { title: 'This is my page', user: req.user });
});
That console.log(req.session) does show me that the req.user has been correctly inserted into the session object and is visible. Authentication.redirectIfNotAuthenticated is using passportjs and is really simple (code included incase it is the issue):
redirectIfNotAuthenticated : function(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/');
}
So...we know that the user is being inserted as a property into the session object...but when I hit one of my socketio methods:
socket.on('init', function(info) {
console.log(socket.session);
...
});
That console.log(socket.session) does not show the session that I modified in the route, but shows the "original" session object - as though I never added anything to it at all! I do know that socket.on('init'... is being called after my io.use(function.... code as detailed above (where the session is pulled from the sessionStore and saved in the socket object).
I just haven't been able to track down why the session, as stored in socket.session (as retrieved from the session store), isn't mirroring the latest changes made to the session in the router.
If anyone has any suggestions, or reasons why what I expect to see is incorrect, I would be happy to hear them!
A session scopes a connection between a dedicated client browser tab and a server.
As you did not explain why you want to store the username in the session I can base my answer only on guesses:
If you want to remember the username for later use in the session store it on the client side.
If you want to declare the user name (and other variables) to other users in the communication space the easiest way to do that is to store the data in a database (mind that databases can be in-memory, which works out to be quick). You could also fittle with files - but if you run mutliple users you will have to switch to a database anyway...
In any way there is no need to extend the scope of a session over multiple clients.