• This repository has been archived on 28/Sep/2021
  • Stars
    star
    659
  • Rank 65,982 (Top 2 %)
  • Language
    JavaScript
  • Created over 11 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

access passport.js authenticated user information from socket.io connection

This module is currently deprecated and unmaintained. Please check #148 which explain how to do this with modern versions of socket.io and using passport directly.

passport.socketio

Access passport.js user information from a socket.io connection.

Installation

npm install passport.socketio

Example usage

// initialize our modules
var io               = require("socket.io")(server),
    sessionStore     = require('awesomeSessionStore'), // find a working session store (have a look at the readme)
    passportSocketIo = require("passport.socketio");

// With Socket.io < 1.0
io.set('authorization', passportSocketIo.authorize({
  cookieParser: express.cookieParser,
  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
}));

//With Socket.io >= 1.0
io.use(passportSocketIo.authorize({
  cookieParser: cookieParser,       // the same middleware you registrer in express
  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);

  // OR

  // If you use [email protected] the callback looks different
  accept();
}

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);

  // OR

  // If you use [email protected] the callback looks different
  // If you don't want to accept the connection
  if(error)
    accept(new Error(message));
  // this error will be sent to the user as a special error-package
  // see: http://socket.io/docs/client-api/#socket > error-object
}

passport.socketio - Options

store [function] required:

Always provide one. If you don't know what sessionStore to use, have a look at this list. 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.

You can also check the simple example below using a redis store.

//in your app.js
var sessionStore = new redisStore();

app.use(session({
  key: 'express.sid',
  store: sessionStore,
  secret: 'keyboard cat'
}));

//in your passport.socketio setup
//With Socket.io >= 1.0 (you will have the same setup for Socket.io <1)
io.use(passportSocketIo.authorize({
  cookieParser: require('cookie-parser'), //optional your cookie-parser middleware function. Defaults to require('cookie-parser')
  key:          'express.sid',       //make sure is the same as in your session settings in app.js
  secret:       'keyboard cat',      //make sure is the same as in your session settings in app.js
  store:        sessionStore,        //you need to use the same sessionStore you defined in the app.use(session({... in app.js
  success:      onAuthorizeSuccess,  // *optional* callback on success
  fail:         onAuthorizeFail,     // *optional* callback on fail/error
}));

cookieParser [function] optional:

Optional cookieParser from express. Express 3 is express.cookieParser in Express 4 require('cookie-parser').

Defaults to require('cookie-parser').

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 if you use socket.io under 1.0:

// accept connection
accept(null, true);

// reject connection (for whatever reason)
accept(null, false);

And like this if you use the newest version of [email protected]

// accept connection
accept();

// reject connection (for whatever reason)
accept(new Error('optional reason'));

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]): (socket.io @ < 1.X)

/* ... */
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);
}

[email protected]:

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);
  // send the (not-fatal) error-message to the client and deny the connection
  return accept(new Error(message));
}

// or
// This function accepts every client unless there's an critical error
function onAuthorizeFail(data, message, error, accept){
  if(error)  throw new Error(message);
  return accept();
}

You can use the message parameter for debugging/logging/etc uses.

socket.handshake.user (prior to v1)

This property was removed in v1. See socket.request.user

socket.request.user (as of v1)

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.request.user.logged_in property which tells you whether the user is currently authorized or not.

Note: This property was named socket.handshake.user prior to v1

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:

passportSocketIo.filterSocketsByUser(io, function(user){
  return user.gender === 'female';
}).forEach(function(socket){
  socket.emit('messsage', 'hello, woman!');
});

CORS-Workaround:

If you happen to have to work with Cross-Origin-Requests (marked by socket.io v0.9 as handshake.xdomain and by socket.io v1.0 as request.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' }));

// 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 (socket.request.xdomain === true with socket.io v1) as there are no cookies sent. For a workaround look at the code above.

Contribute

You are always welcome to open an issue or provide a pull-request! Also check out the unit tests:

npm test

License

Licensed under the MIT-License. 2012-2013 JosΓ© F. Romaniello.

More Repositories

1

url-join

Join all arguments together and normalize the resulting url.
JavaScript
344
star
2

winser

Run a node.js application as a window service using nssm.
JavaScript
270
star
3

selfsigned

Generate self-signed certificates from node.js
JavaScript
223
star
4

express-unless

Conditionally add a middleware to express with some common patterns
TypeScript
171
star
5

pswatch

Powershell cmdlet to monitor file changes in a directory tree.
79
star
6

node-gpstracker

server library for a GPS / GPRS tracker
JavaScript
51
star
7

node-windows-eventlog

Native node.js module to log messages to the Windows EventLog
C++
44
star
8

li

JavaScript utility to parse and generate the Link header according to RFC 5988.
JavaScript
41
star
9

Grandson-of-Obsidian

Textmate theme inspired in Obsidian
39
star
10

sublime-node-require

helper to add require clauses to node.js modules in Sublime Text 2
Python
38
star
11

zero-downtime-node

JavaScript
36
star
12

sublime-html-to-jade

Sublime Text 2 plugin to convert html file, selection or clipboard to jade.
Python
27
star
13

lru-memoizer

Memoize functions results using an lru-cache.
JavaScript
26
star
14

Sublime-Package-Decontrol

Like Sublime Package Control but without a central repository.
Python
26
star
15

sublime-mocha-snippets

sublime 2 snippets for the mocha testing framework
23
star
16

passport-hawk

Passport strategy for the Hawk authentication schema.
JavaScript
22
star
17

npm-install-retry

Command line utility that retries `npm install` when NPM fails with `npm ERR! cb() never called`
JavaScript
21
star
18

mac-ca

Get Mac OS Root certificates in node.js
TypeScript
20
star
19

node-windows-certs

Get certificates from the windows cert store from node.js
JavaScript
19
star
20

refresh-token

Helper to get a valid oauth 2 token given a refresh token.
JavaScript
16
star
21

parse-links

Parse a Links header into a JavaScript object.
JavaScript
15
star
22

mongo-getdb

A very opinionated way to connect with the mongodb driver.
JavaScript
13
star
23

RazorCandle

Render a razor template and save it to a file from command line.
C#
11
star
24

mockuire

require a module with mocked dependencies in node.js
JavaScript
11
star
25

winston-winlog

Windows Event Log logger for the node.js Winston module.
JavaScript
9
star
26

slido

A web application to generate HTML5 slideshow from markdown.
JavaScript
9
star
27

passport-sharejs

Use passport.js user profile from session to authorize operations on Share.js documents.
JavaScript
9
star
28

teamcity-badges

Teamcity Badges
JavaScript
8
star
29

nestin

Visual Studio extension to "nest" files in the Solution Explorer.
XSLT
8
star
30

fstream-s3

Advanced FS streaming to amazon s3 for Node
JavaScript
8
star
31

sns-subscribe-internal

Subscribe an SNS Topic to an internal webhook.
JavaScript
8
star
32

master-process

reload node.js apps with no downtime
JavaScript
7
star
33

npm-preserve

Shell
6
star
34

strider-hipchat

Strider plugin for hipchat
JavaScript
6
star
35

ejs-amd

standalone and express/connect middleware to serve EJS template as AMD .js files to the browser
JavaScript
5
star
36

LongPollingChat

C#
4
star
37

socket-io.sessions

access express.js session from socket.io
JavaScript
4
star
38

rendirect

Express middleware to render a message and redirect the browser
JavaScript
4
star
39

dynamodb-subscriber

Subscribe to DynamoDB streams easily.
JavaScript
4
star
40

fix-github-tabs

JavaScript
3
star
41

ss-to-db

Send screenshot to dropbox (Mac only)
JavaScript
3
star
42

tortu

AJLogo command line interpreter
JavaScript
3
star
43

xtail

Restart, stop or start service while watching its log file.
JavaScript
3
star
44

sublime-goto-node-module

Open the homepage of any node module installed (or native)
Python
3
star
45

extract

JavaScript
3
star
46

envcredstash

JavaScript
3
star
47

uqbar

JavaScript
3
star
48

jmail

An example of single page web application driven by unit tests
JavaScript
3
star
49

very-fast-args

JavaScript
2
star
50

visa-analyzer

JavaScript
2
star
51

funstream

Functional programming operations with node.js streams (nothing here yet)
CoffeeScript
2
star
52

xenv

JavaScript
2
star
53

alerta-cookbook

Chef cookbook for alerta
Ruby
2
star
54

iSqlCmd

Enhanced Sql Server Command Line interface
C#
2
star
55

hashi

an AMD polyfill for hashchange
JavaScript
2
star
56

put-blob

send file to blob storage from command line
JavaScript
2
star
57

sublime-unity-recents

Sublime Text 2 plugin to automatically keep a list of the ten last folders opened in the Ubuntu Unity launcher.
Python
2
star
58

jam-jade-runtime

Amd jade runtime for the JAM package system.
JavaScript
2
star
59

cose-kit

TypeScript
2
star
60

zq

An AMD module to manipulate the DOM, combining three small libraries that works for me and might work for you
JavaScript
1
star
61

pb-stream

Protobuf.js stream encoder / decoder for varint32 length-delimited messages.
JavaScript
1
star
62

chinooktest

1
star
63

tvpublica-roku

Roku channel for TV Publica - Canal 7 - Argentina.
Brightscript
1
star
64

pshare

stream something to a public url
JavaScript
1
star
65

json-docker

the json command line utility built into a docker image
Shell
1
star
66

ts-env-parser

TypeScript
1
star
67

css-import

merge css files with @import clause
JavaScript
1
star
68

s2s3

Take a snapshot and send it to s3. (OSx only)
JavaScript
1
star
69

tedemo

a demo application to show how to share jade templates to the browser
JavaScript
1
star
70

gdrivesdk

this is the example of the google drive sdk, nothing to see here
JavaScript
1
star
71

recurse-delete-property

Delete property recursively
JavaScript
1
star
72

chato

pet project chat with websockets
JavaScript
1
star
73

yams

Yet Another MongoDb Session Store
JavaScript
1
star
74

gapps-provisioning

(Unofficial) Google Apps Provisioning Api client library for node.js
JavaScript
1
star
75

my-console2

my console2 configuration
1
star
76

slice-of-life

Helper functions to create paginated REST APIs in node.js.
JavaScript
1
star
77

prismcontrib

Prism Contrib fork for Prism v3
C#
1
star
78

fizzbuzz-js

Ejemplo FizzBuzz en Js - CodeCampBA
JavaScript
1
star
79

har-sanitizer

HAR archive sanitizer
TypeScript
1
star