Add a JWT token authentication

This commit is contained in:
Olivier MICHAUD
2021-05-17 21:46:55 +02:00
parent 3c06736520
commit 1371d03fec
5 changed files with 200 additions and 4 deletions
+28 -3
View File
@@ -1,8 +1,9 @@
import request from 'supertest';
import assert from 'assert';
import { Server as WebSocketServer } from 'ws';
import WebSocket from 'ws';
import WebSocket, {Server as WebSocketServer} from 'ws';
import net from 'net';
import jwt from 'jsonwebtoken';
import createServer from './server';
@@ -34,6 +35,30 @@ describe('Server', () => {
assert.equal(res.body.message, 'Invalid subdomain. Subdomains must be lowercase and between 4 and 63 alphanumeric characters.');
});
it('reject request without jwt if required', async () => {
const server = createServer({jwt_shared_secret: 'thekey'});
const res = await request(server).get('/subdomain');
assert.equal(res.status, 401);
});
it('reject request with invalid jwt if required', async () => {
const server = createServer({jwt_shared_secret: 'thekey'});
const jwtoken = jwt.sign({
foo: 'bar'
}, 'thebadkey');
const res = await request(server).get('/subdomain').set('Authorization', `Bearer ${jwtoken}`);
assert.equal(res.status, 401);
});
it('accept request with valid jwt if required', async () => {
const server = createServer({jwt_shared_secret: 'thekey'});
const jwtoken = jwt.sign({
foo: 'bar'
}, 'thekey');
const res = await request(server).get('/subdomain').set('Authorization', `Bearer ${jwtoken}`);
assert.equal(res.status, 200);
});
it('should upgrade websocket requests', async () => {
const hostname = 'websocket-test';
const server = createServer({
@@ -106,4 +131,4 @@ describe('Server', () => {
await new Promise(resolve => server.close(resolve));
});
});
});