initial commit after fork of passport-socketio

This commit is contained in:
José F. Romaniello 2014-01-13 16:00:21 -03:00
parent aa678b4dd9
commit 14a34ae380
9 changed files with 131 additions and 391 deletions

139
README.md
View File

@ -1,155 +1,48 @@
# passport.socketio Authenticate socket.io incoming connections with JWTs. This is useful if you are build a single page application and you are not using cookies as explained in this blog post: [Cookies vs Tokens. Getting auth right with Angular.JS](http://blog.auth0.com/2014/01/07/angularjs-authentication-with-cookies-vs-token/).
> Access [passport.js](http://passportjs.org) user information from a [socket.io](http://socket.io) connection.
## Installation ## Installation
``` ```
npm install passport.socketio npm install socketio-jwt
``` ```
## Example usage ## Example usage
```javascript ```javascript
var io = require("socket.io")(server);
// initialize our modules var socketioJwt = require("socketio-jwt");
var io = require("socket.io")(server),
sessionStore = require('awesomeSessionStore'), // find a working session store (have a look at the readme)
passportSocketIo = require("passport.socketio");
// set authorization for socket.io // set authorization for socket.io
io.set('authorization', passportSocketIo.authorize({ io.set('authorization', socketioJwt.authorize({
cookieParser: express.cookieParser, secret: 'your secret or public key'
key: 'express.sid', // the name of the cookie where express/connect stores its session_id
secret: 'session_secret', // the session_secret to parse the cookie
store: sessionStore, // we NEED to use a sessionstore. no memorystore please
success: onAuthorizeSuccess, // *optional* callback on success - read more below
fail: onAuthorizeFail, // *optional* callback on fail/error - read more below
})); }));
function onAuthorizeSuccess(data, accept){
console.log('successful connection to socket.io');
// The accept-callback still allows us to decide whether to
// accept the connection or not.
accept(null, true);
}
function onAuthorizeFail(data, message, error, accept){
if(error)
throw new Error(message);
console.log('failed connection to socket.io:', message);
// We use this callback to log all of our failed connections.
accept(null, false);
}
``` ```
## passport.socketio - Options For more validation options see [auth0/jsonwebtoken](https://github.com/auth0/node-jsonwebtoken).
### `store` [function] **required**: __Client side__:
*Always* provide one. If you don't know what sessionStore to use, have a look at [this list](https://github.com/senchalabs/connect/wiki#session-stores).
Also be sure to use the same sessionStore or at least a connection to *the same collection/table/whatever*. And don't forget your `express.session()` middleware:
`app.use(express.session({ store: awesomeSessionStore }));`
For further info about this middleware see [the official documentation](http://www.senchalabs.org/connect/session.html#session).
### `cookieParser` [function] **required**: For now the only way to append the jwt token is using query string:
You have to provide your cookieParser from express: `express.cookieParser`
### `key` [string] **optional**:
Defaults to `'connect.sid'`. But you're always better of to be sure and set your own key. Don't forget to also change it in your `express.session()`:
`app.use(express.session({ key: 'your.sid-key' }));`
### `secret` [string] **optional**:
As with `key`, also the secret you provide is optional. *But:* be sure to have one. That's always safer. You can set it like the key:
`app.use(express.session({ secret: 'pinkie ate my cupcakes!' }));`
### `passport` [function] **optional**:
Defaults to `require('passport')`. If you want, you can provide your own instance of passport for whatever reason.
### `success` [function] **optional**:
Callback which will be called everytime a *authorized* user successfuly connects to your socket.io instance. **Always** be sure to accept/reject the connection.
For that, there are two parameters: `function(data[object], accept[function])`. `data` contains all the user-information from passport.
The second parameter is for accepting/rejecting connections. Use it like this:
```javascript ```javascript
// accept connection var socket = io.connect('http://localhost:9000', {
accept(null, true); 'query': 'token=' + your_jwt
// reject connection (for whatever reason)
accept(null, false);
```
### `fail` [function] **optional**:
The name of this callback may be a little confusing. While it is called when a not-authorized-user connects, it is also called when there's a error.
For debugging reasons you are provided with two additional parameters `function(data[object], message[string], error[bool], accept[function])`:
```javascript
/* ... */
function onAuthorizeFail(data, message, error, accept){
// error indicates whether the fail is due to an error or just a unauthorized client
if(error){
throw new Error(message);
} else {
console.log(message);
// the same accept-method as above in the success-callback
accept(null, false);
}
}
// or
// This function accepts every client unless there's an error
function onAuthorizeFail(data, message, error, accept){
console.log(message);
accept(null, !error);
}
```
You can use the `message` parameter for debugging/logging/etc uses.
## `socket.handshake.user`
This property is always available from inside a `io.on('connection')` handler. If the user is authorized via passport, you can access all the properties from there.
**Plus** you have the `socket.handshake.user.logged_in` property which tells you whether the user is currently authorized or not.
## Additional methods
### `passportSocketIo.filterSocketsbyUser`
This function gives you the ability to filter all connected sockets via a user property. Needs two parameters `function(io, function(user))`. Example:
```javascript
passportSocketIo.filterSocketsByUser(io, function(user){
return user.gender === 'female';
}).forEach(function(socket){
socket.emit('messsage', 'hello, woman!');
}); });
``` ```
## CORS-Workaround: Take care as URLs has a lenght limitation on Internet Explorer. I opened a [issue in engine-io-client](https://github.com/LearnBoost/engine.io-client/issues/228) to support headers.
If you happen to have to work with Cross-Origin-Requests (marked by socket.io as `handshake.xdomain`) then here's a workaround:
### Clientside:
You have to provide the session-cookie. If you haven't set a name yet, do it like this: `app.use(express.session({ key: 'your.sid-key' }));`
```javascript
// Note: ther's no readCookie-function built in.
// Get your own in the internetz
socket = io.connect('//' + window.location.host, {
query: 'session_id=' + readCookie('your.sid-key')
});
```
### Serverside:
Nope, there's nothing to do on the server side. Just be sure that the cookies names match.
## Notes:
* Does **NOT** support cookie-based sessions. eg: `express.cookieSession`
* If the connection fails, check if you are requesting from a client via CORS. Check `socket.handshake.xdomain === true` as there are no cookies sent. For a workaround look at the code above.
## Contribute ## Contribute
You are always welcome to open an issue or provide a pull-request! You are always welcome to open an issue or provide a pull-request!
Also check out the unit tests: Also check out the unit tests:
```bash ```bash
npm test npm test
``` ```
## License ## License
Licensed under the MIT-License. Licensed under the MIT-License.
2012-2013 José F. Romaniello. 2013 AUTH10 LLC.

11
lib/UnauthorizedError.js Normal file
View File

@ -0,0 +1,11 @@
function UnauthorizedError (code, error) {
Error.call(this, error.message);
this.message = error.message;
this.code = code;
this.inner = error;
}
UnauthorizedError.prototype = Object.create(Error.prototype);
UnauthorizedError.prototype.constructor = UnauthorizedError;
module.exports = UnauthorizedError;

View File

@ -1,71 +1,62 @@
var xtend = require('xtend'); var xtend = require('xtend');
var jwt = require('jsonwebtoken');
function parseCookie(auth, cookieHeader) { var UnauthorizedError = require('./UnauthorizedError');
var cookieParser = auth.cookieParser(auth.secret); var url = require('url');
var req = {
headers:{
cookie: cookieHeader
}
};
var result;
cookieParser(req, {}, function (err) {
if (err) throw err;
result = req.signedCookies;
});
return result;
}
function authorize(options) { function authorize(options) {
var defaults = { var defaults = {
passport: require('passport'), success: function(data, accept){
key: 'connect.sid', accept(null, true);
secret: null, },
store: null, fail: function(error, data, accept){
success: function(data, accept){accept(null, true)}, accept(null, false);
fail: function(data, message, critical, accept){accept(null, false)} }
}; };
var auth = xtend(defaults, options); var auth = xtend(defaults, options);
auth.userProperty = auth.passport._userProperty || 'user'; return function(data, accept){
var token, error;
if (!auth.cookieParser) { if (data.headers && data.headers.authorization) {
throw new Error('cookieParser is required use connect.cookieParser or express.cookieParser'); var parts = data.headers.authorization.split(' ');
if (parts.length == 2) {
var scheme = parts[0],
credentials = parts[1];
if (/^Bearer$/i.test(scheme)) {
token = credentials;
}
} else {
error = new UnauthorizedError('credentials_bad_format', {
message: 'Format is Authorization: Bearer [token]'
});
return auth.fail(error, data, accept);
}
} }
return function(data, accept){ if (data.query.token) {
data.cookie = parseCookie(auth, data.headers.cookie || ''); token = data.query.token;
data.sessionID = data.query.session_id || data.cookie[auth.key] || ''; }
data[auth.userProperty] = {
logged_in: false
};
if(data.xdomain && !data.sessionID) if (!token) {
return auth.fail(data, 'Can not read cookies from CORS-Requests. See CORS-Workaround in the readme.', false, accept); error = new UnauthorizedError('credentials_required', {
message: 'No Authorization header was found'
auth.store.get(data.sessionID, function(err, session){
if(err)
return auth.fail(data, 'Error in session store:\n' + err.message, true, accept);
if(!session)
return auth.fail(data, 'No session found', false, accept);
if(!session[auth.passport._key])
return auth.fail(data, 'Passport was not initialized', true, accept);
var userKey = session[auth.passport._key][auth.userProperty];
if(!userKey)
return auth.fail(data, 'User not authorized through passport. (User Property not found)', false, accept);
auth.passport.deserializeUser(userKey, function(err, user) {
if (err)
return auth.fail(data, err, true, accept);
if (!user)
return auth.fail(data, "User not found", false, accept);
data[auth.userProperty] = user;
data[auth.userProperty].logged_in = true;
auth.success(data, accept);
}); });
return auth.fail(error, data, accept);
}
jwt.verify(token, options.secret, options, function(err, decoded) {
if (err) {
error = new UnauthorizedError('invalid_token', err);
return auth.fail(error, data, accept);
}
data.user = decoded;
data.logged_in = true;
auth.success(data, accept);
}); });
}; };
} }

View File

@ -1,33 +1,34 @@
{ {
"name": "passport.socketio", "name": "socketio-jwt",
"version": "2.2.1", "version": "1.0.0",
"description": "access passport.js authenticated user information from socket.io", "description": "authenticate socket.io connections using JWTs",
"main": "lib/index.js", "main": "lib/index.js",
"keywords": [ "keywords": [
"socket", "socket",
"socket.io", "socket.io",
"passport" "jwt"
], ],
"author": { "author": {
"name": "José F. Romaniello", "name": "José F. Romaniello",
"email": "jfromaniello@gmail.com" "email": "jfromaniello@gmail.com",
"url": "http://joseoncode.com"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
"url": "https://github.com/jfromaniello/passport.socketio.git" "url": "https://github.com/auth0/socketio-jwt.git"
}, },
"scripts": { "scripts": {
"test": "mocha" "test": "mocha"
}, },
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"passport": "~0.1.16", "jsonwebtoken": "~0.1.0",
"xtend": "~2.0.3" "xtend": "~2.0.3"
}, },
"devDependencies": { "devDependencies": {
"request": "~2.19.0", "request": "~2.19.0",
"should": "~1.2.2", "should": "~1.2.2",
"mocha": "~1.9.0", "mocha": "~1.17.0",
"express": "~3.1.2", "express": "~3.1.2",
"socket.io": "~0.9.14", "socket.io": "~0.9.14",
"passport-local": "~0.1.6", "passport-local": "~0.1.6",

View File

@ -1,7 +1,5 @@
var fixture = require('./fixture'), var fixture = require('./fixture');
request = require('request'), var request = require('request');
setSocketIOHandshakeCookies = require('./fixture/setSocketIOHandshakeCookies');
var io = require('socket.io-client'); var io = require('socket.io-client');
describe('authorizer', function () { describe('authorizer', function () {
@ -10,17 +8,14 @@ describe('authorizer', function () {
before(fixture.start); before(fixture.start);
after(fixture.stop); after(fixture.stop);
//create a new session for every test
beforeEach(function(){
this.cookies = request.jar();
setSocketIOHandshakeCookies(this.cookies);
});
describe('when the user is not logged in', function () { describe('when the user is not logged in', function () {
it('should emit error with unauthorized handshake', function (done){ it('should emit error with unauthorized handshake', function (done){
var socket = io.connect('http://localhost:9000', {'force new connection':true}); var socket = io.connect('http://localhost:9000', {
'query': 'token=Booooooooooooooooooooo',
'force new connection': true
});
socket.on('error', function(err){ socket.on('error', function(err){
err.should.eql('handshake unauthorized'); err.should.eql('handshake unauthorized');
done(); done();
@ -33,19 +28,24 @@ describe('authorizer', function () {
beforeEach(function (done) { beforeEach(function (done) {
request.post({ request.post({
jar: this.cookies,
url: 'http://localhost:9000/login', url: 'http://localhost:9000/login',
form: {username: 'jose', password: 'Pa123'} form: { username: 'jose', password: 'Pa123' },
}, done); json: true
}, function (err, resp, body) {
this.token = body.token;
done();
}.bind(this));
}); });
it('should do the handshake and connect', function (done){ it('should do the handshake and connect', function (done){
var socket = io.connect('http://localhost:9000', {'force new connection':true}); var socket = io.connect('http://localhost:9000', {
'force new connection':true,
'query': 'token=' + this.token
});
socket.on('connect', function(){ socket.on('connect', function(){
done(); done();
}).on('error', done); }).on('error', done);
}); });
}); });
}); });

View File

@ -1,97 +0,0 @@
var fixture = require('./fixture'),
request = require('request'),
setSocketIOHandshakeCookies = require('./fixture/setSocketIOHandshakeCookies');
var io = require('socket.io-client');
describe('authorizer with success callback', function () {
//stop the server
afterEach(fixture.stop);
//start the server
//create a new session for every test
beforeEach(function(done){
this.cookies = request.jar();
setSocketIOHandshakeCookies(this.cookies);
fixture.start({
success: function(data, accept){
this.accept = accept;
}.bind(this)
}, done);
});
it('should call the success function with accept', function (done){
request.post({
jar: this.cookies,
url: 'http://localhost:9000/login',
form: {username: 'jose', password: 'Pa123'}
}, function(){
io.connect('http://localhost:9000', {'force new connection':true});
setTimeout(function(){
this.accept
.should.be.instanceOf(Function);
done();
}.bind(this), 300);
}.bind(this));
});
it('should not connect until calling the accept function', function (done){
request.post({
jar: this.cookies,
url: 'http://localhost:9000/login',
form: {username: 'jose', password: 'Pa123'}
}, function(){
var connected = false,
socket = io.connect('http://localhost:9000', {'force new connection':true});
socket.on('connect', function(){
connected = true;
}).on('error', done);
setTimeout(function(){
connected.should.be.false;
done();
}.bind(this), 300);
}.bind(this));
});
it('should connect after calling the accept function', function (done){
request.post({
jar: this.cookies,
url: 'http://localhost:9000/login',
form: {username: 'jose', password: 'Pa123'}
}, function(){
var connected = false,
socket = io.connect('http://localhost:9000', {'force new connection':true});
socket.on('connect', function(){
connected = true;
}).on('error', done);
setTimeout(function(){
this.accept(null, true);
setTimeout(function(){
connected.should.be.true;
done();
}, 200);
}.bind(this), 200);
}.bind(this));
});
});

View File

@ -1,68 +1,52 @@
var express = require('express'), var express = require('express');
connect = require('connect'), var http = require('http');
passport = require('passport'),
http = require('http'),
xtend = require('xtend');
var socketIo = require('socket.io'), var socketIo = require('socket.io');
passportSocketIo = require('../../lib'); var socketio_jwt = require('../../lib');
var sessionStore = new connect.session.MemoryStore(), var jwt = require('jsonwebtoken');
sessionSecret = 'asdasdsdas1312312',
sessionKey = 'test-session-key', var xtend = require('xtend');
sessionOptions = {
store: sessionStore,
key: sessionKey,
secret: sessionSecret
};
var server; var server;
require('./setupPassport');
exports.start = function (options, callback) { exports.start = function (options, callback) {
if(typeof options == 'function'){ if(typeof options == 'function'){
callback = options; callback = options;
options = { options = {};
};
} }
options.cookieParser = express.cookieParser;
options = xtend({ secret: 'aaafoo super sercret'}, options);
var app = express(); var app = express();
app.configure(function(){ app.configure(function(){
app.use(express.cookieParser()); this.use(express.json());
this.use(express.urlencoded());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session(sessionOptions));
app.use(passport.initialize());
app.use(passport.session());
}); });
app.post('/login', passport.authenticate('local', { successRedirect: '/', app.post('/login', function (req, res) {
failureRedirect: '/login', var profile = {
failureFlash: true })); first_name: 'John',
last_name: 'Doe',
email: 'john@doe.com',
id: 123
};
app.get('/', function(req, res){ // We are sending the profile inside the token
if(!req.user){ var token = jwt.sign(profile, options.secret, { expiresInMinutes: 60*5 });
res.send(401);
}else{ res.json({token: token});
res.json(req.user);
}
}); });
server = http.createServer(app); server = http.createServer(app);
var sio = socketIo.listen(server); var sio = socketIo.listen(server);
sio.configure(function(){ sio.configure(function(){
this.set('authorization', passportSocketIo.authorize(xtend(sessionOptions, options))); this.set('authorization', socketio_jwt.authorize(options));
this.set('log level', 0); this.set('log level', 0);
}); });
sio.sockets.on('echo', function (m) { sio.sockets.on('echo', function (m) {

View File

@ -1,20 +0,0 @@
var xmlhttprequest = require('xmlhttprequest');
var originalRequest = xmlhttprequest.XMLHttpRequest;
module.exports = function (jar) {
xmlhttprequest.XMLHttpRequest = function(){
originalRequest.apply(this, arguments);
this.setDisableHeaderCheck(true);
var stdOpen = this.open;
this.open = function() {
stdOpen.apply(this, arguments);
var header = jar.get({ url: 'http://localhost:9000' })
.map(function (c) {
return c.name + "=" + c.value;
}).join("; ");
this.setRequestHeader('cookie', header);
};
};
};

View File

@ -1,23 +0,0 @@
var passport = require('passport'),
LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy(
function(username, password, done) {
if(username === 'jose' && password === 'Pa123'){
return done(null, {
name: 'jose',
mail: 'j@f.r'
});
} else {
return done(null, false, {message: 'wrong user name or password'});
}
}
));
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});