You're close, though I'd recommend setting a request header over setting a query string param. The data
variable in your authorization function is handshake data that contains request header and cookie information you can use. Here's an example with setting a cookie:
On the server
io.configure(function() {
io.set('authorization', function(handshake, callback) {
var cookie, token, authPair, parts;
// check for headers
if (handshake.headers.cookie &&
handshake.headers.cookie.split('=')[0]=='myapp') {
// found request cookie, parse it
cookie = handshake.headers.cookie;
token = cookie.split(/s+/).pop() || '';
authPair = new Buffer(token, 'base64').toString();
parts = authPair.split(/:/);
if (parts.length>=1) {
// assume username & pass provided, check against db
// parts[0] is username, parts[1] is password
// .... {db checks}, then if valid....
callback(null, true);
} else if(parts.length==1) {
// assume only username was provided @ parts[0]
callback(null,true);
} else {
// not what we were expecting
callback(null, false);
}
}
else {
// auth failed
callback(null, false);
}
});
});
On the client
Before you call socket.connect
, set a cookie with your auth / user info:
function writeCookie(value, days) {
var date, expires;
// days indicates how long the user's session should last
if (days) {
date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires="+date.toGMTString();
} else {
expires = "";
}
document.cookie = "myapp="+Base64.encode(value)+expires+"; path=/";
};
// for a 'viewer' user:
writeCookie('usernameHere', 1);
// for the 'host' user:
writeCookie('usernameHere:passwordHere', 1);
You'll need a Base64 library on the client side unless your browser supports btoa()
.
It's important to note that this isn't a good authentication structure. Passing user credentials straight in either query strings or header information is not secure. This method gets you closer to a more secure method, though. I'd recommend looking into an auth library like passport.js or everyauth. You can sub-in this code to utilize the session information those libraries store in running your checks.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…