ws-basic-auth-express

Adds basic auth to socket connections in express

Usage no npm install needed!

<script type="module">
  import wsBasicAuthExpress from 'https://cdn.skypack.dev/ws-basic-auth-express';
</script>

README

Overview

Adds basic auth to socket connections in express. Only tested with ws. Socket.io is not supported.

Example

var express = require('express');
var wsBasicAuth = require("ws-basic-auth-express");
var http = require('http');
var WebSocketServer = require('ws').Server

var app = express();
var server = http.createServer(app);
var wss = new WebSocketServer({server: server});

var wsAuth = wsBasicAuth(function(username, password) {
  return username === process.env.USERNAME && password === process.env.PASSWORD;
});

#All upgrade requests go through auth
server.on('upgrade', wsAuth);

Credits

The basic auth code was borrowed from basic-auth-connect

The connection abort code was borrowed from ws.