LoginSignup
16
10

More than 5 years have passed since last update.

Socket.IO でユーザー認証

Posted at

Socket.IO で接続してきたクライアントが正規ユーザーかどうかの認証を行う。

環境

  • Node.js: 10.10.0
  • Socket.IO: 2.1.1

middleware について

Socket.IO の namespace.use(fn) を使用して、接続してきたソケットをハンドリングするミドルウェアを登録することができる。

io.use((socket, next) => {
  if (socket.request.headers.cookie) return next()
  next(new Error('Authentication error'))
})

サーバー側

Socket.IO — Client API | Socket.IO

// server-side
const io = require('socket.io')();

// middleware
io.use((socket, next) => {
  let token = socket.handshake.query.token;
  if (isValid(token)) {
    return next();
  }
  return next(new Error('authentication error'));
});

// then
io.on('connection', (socket) => {
  // 認証に失敗した場合 connection イベントは発火しない
  // do something...
});

クライアント側

接続

// クライアント
const socket = io('http://localhost', {
  query: {
    token: 'abc'
  }
})
socket.on('connect', () => {
  // 認証に失敗した場合 connect イベントは発火しない
  // do something...
})

トークンの更新

再接続のときにクエリの内容を更新することができる。

socket.on('reconnect_attempt', () => {
  socket.io.opts.query = {
    token: 'def'
  }
})
16
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
10