Compare commits
25 Commits
Author | SHA1 | Date | |
---|---|---|---|
88bfd46c33 | |||
4b95cd4293 | |||
c7f64a6312 | |||
89518a45d5 | |||
a5da945bb5 | |||
ce798241e5 | |||
8dfddbd5b4 | |||
e353d2a1fe | |||
5a02e25f86 | |||
f9678604cc | |||
c5121fb008 | |||
95e461540a | |||
7687ddfe83 | |||
565f83db9d | |||
6953d6952b | |||
3d109f362f | |||
ced2f5db1e | |||
0971dcc1bb | |||
a710630ccf | |||
e50e7ea00e | |||
cff7892c3d | |||
17232c18e1 | |||
8f896eb93b | |||
814fc781e3 | |||
4291da1417 |
6
.github/ISSUE_TEMPLATE/DOCUMENTATION.md
vendored
6
.github/ISSUE_TEMPLATE/DOCUMENTATION.md
vendored
@ -5,11 +5,7 @@ title: '[Documentation]'
|
||||
labels: 'documentation'
|
||||
---
|
||||
|
||||
<!--
|
||||
Please make sure your issue has not already been fixed.
|
||||
|
||||
Please place an x (no spaces - [x]) in all [ ] that apply.
|
||||
-->
|
||||
<!-- Please make sure your issue has not already been fixed. -->
|
||||
|
||||
## Documentation
|
||||
|
||||
|
6
.github/ISSUE_TEMPLATE/IMPROVEMENT.md
vendored
6
.github/ISSUE_TEMPLATE/IMPROVEMENT.md
vendored
@ -5,11 +5,7 @@ title: '[Improvement]'
|
||||
labels: 'improvement'
|
||||
---
|
||||
|
||||
<!--
|
||||
Please make sure your issue has not already been fixed.
|
||||
|
||||
Please place an x (no spaces - [x]) in all [ ] that apply.
|
||||
-->
|
||||
<!-- Please make sure your issue has not already been fixed. -->
|
||||
|
||||
## Type of Improvement
|
||||
|
||||
|
4
.github/PULL_REQUEST_TEMPLATE.md
vendored
4
.github/PULL_REQUEST_TEMPLATE.md
vendored
@ -3,9 +3,7 @@
|
||||
Please first discuss the change you wish to make via issue before making a change. It might avoid a waste of your time.
|
||||
|
||||
Before submitting your contribution, please take a moment to review this document:
|
||||
https://github.com/Thream/socketio-jwt/blob/master/.github/CONTRIBUTING.md
|
||||
|
||||
Please place an x (no spaces - [x]) in all [ ] that apply.
|
||||
https://github.com/Thream/socketio-jwt/blob/master/CONTRIBUTING.md
|
||||
|
||||
-->
|
||||
|
||||
|
4
.github/workflows/commitlint.yml
vendored
4
.github/workflows/commitlint.yml
vendored
@ -17,4 +17,6 @@ jobs:
|
||||
- uses: 'actions/checkout@v2'
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: 'wagoid/commitlint-github-action@v2'
|
||||
- uses: 'wagoid/commitlint-github-action@v3.0.6'
|
||||
with:
|
||||
configFile: '.commitlintrc.json'
|
||||
|
8
.github/workflows/nodejs.yml
vendored
8
.github/workflows/nodejs.yml
vendored
@ -20,18 +20,18 @@ jobs:
|
||||
- uses: 'actions/checkout@v2'
|
||||
|
||||
- name: Use Node.js ${{ matrix.node-version }}
|
||||
uses: 'actions/setup-node@v2.1.4'
|
||||
uses: 'actions/setup-node@v2.1.5'
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
|
||||
- name: 'Cache dependencies'
|
||||
uses: 'actions/cache@v2.1.4'
|
||||
with:
|
||||
path: '**/node_modules'
|
||||
key: ${{ runner.os }}-${{ hashFiles('**/package.json') }}
|
||||
path: '.npm'
|
||||
key: ${{ runner.os }}-${{ hashFiles('**/package-lock.json') }}
|
||||
|
||||
- name: 'Install dependencies'
|
||||
run: 'npm install'
|
||||
run: 'npm ci --cache .npm --prefer-offline'
|
||||
|
||||
- name: 'Lint'
|
||||
run: 'npm run lint'
|
||||
|
26
.github/workflows/npm-publish.yml
vendored
26
.github/workflows/npm-publish.yml
vendored
@ -12,19 +12,25 @@ jobs:
|
||||
steps:
|
||||
- uses: 'actions/checkout@v2'
|
||||
|
||||
- name: 'Cache dependencies'
|
||||
uses: 'actions/cache@v2.1.4'
|
||||
with:
|
||||
path: '**/node_modules'
|
||||
key: ${{ runner.os }}-${{ hashFiles('**/package.json') }}
|
||||
|
||||
- uses: 'actions/setup-node@v2.1.2'
|
||||
- name: Use Node.js ${{ matrix.node-version }}
|
||||
uses: 'actions/setup-node@v2.1.5'
|
||||
with:
|
||||
node-version: 14
|
||||
registry-url: 'https://registry.npmjs.org/'
|
||||
|
||||
- run: 'npm install'
|
||||
- run: 'npm run build'
|
||||
- run: 'npm publish --access public'
|
||||
- name: 'Cache dependencies'
|
||||
uses: 'actions/cache@v2.1.4'
|
||||
with:
|
||||
path: '.npm'
|
||||
key: ${{ runner.os }}-${{ hashFiles('**/package-lock.json') }}
|
||||
|
||||
- name: 'Install dependencies'
|
||||
run: 'npm ci --cache .npm --prefer-offline'
|
||||
|
||||
- name: 'Build'
|
||||
run: 'npm run build'
|
||||
|
||||
- name: 'Publish package on npm'
|
||||
run: 'npm publish --access public'
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
|
||||
|
15
.gitignore
vendored
15
.gitignore
vendored
@ -2,9 +2,7 @@
|
||||
|
||||
# dependencies
|
||||
node_modules
|
||||
.pnp
|
||||
.pnp.js
|
||||
.yarn
|
||||
.npm
|
||||
|
||||
# production
|
||||
build
|
||||
@ -12,19 +10,8 @@ build
|
||||
# testing
|
||||
coverage
|
||||
|
||||
# envs
|
||||
.env
|
||||
.env.production
|
||||
|
||||
# debug
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
# lockfiles
|
||||
package-lock.json
|
||||
yarn.lock
|
||||
pnpm-lock.yaml
|
||||
|
||||
# editors
|
||||
.vscode
|
||||
|
@ -1,5 +1,11 @@
|
||||
# Changelog
|
||||
|
||||
## [2.1.0](https://github.com/Thream/socketio-jwt/compare/v2.0.0...v2.1.0) (2021-03-08)
|
||||
|
||||
### Features
|
||||
|
||||
- add optional `onAuthentication` option to add `user` property in `socket` object ([#62](https://github.com/Thream/socketio-jwt/issues/62)) ([c7f64a6](https://github.com/Thream/socketio-jwt/commit/c7f64a6312a3e1f6f04918cb7cd415ddef7a11e5))
|
||||
|
||||
## [2.0.0](https://github.com/Thream/socketio-jwt/compare/v1.1.1...v2.0.0) (2021-02-22)
|
||||
|
||||
### Features
|
||||
|
29
README.md
29
README.md
@ -87,10 +87,37 @@ io.on('connection', async (socket) => {
|
||||
})
|
||||
```
|
||||
|
||||
### Server side with `onAuthentication` (example)
|
||||
|
||||
```ts
|
||||
import { Server } from 'socket.io'
|
||||
import { authorize } from '@thream/socketio-jwt'
|
||||
|
||||
const io = new Server(9000)
|
||||
io.use(
|
||||
authorize({
|
||||
secret: 'your secret or public key',
|
||||
onAuthentication: async decodedToken => {
|
||||
// return the object that you want to add to the user property
|
||||
// or throw an error if the token is unauthorized
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
io.on('connection', async (socket) => {
|
||||
// jwt payload of the connected client
|
||||
console.log(socket.decodedToken)
|
||||
// You can do the same things of the previous example there...
|
||||
// user object returned in onAuthentication
|
||||
console.log(socket.user)
|
||||
})
|
||||
```
|
||||
|
||||
### `authorize` options
|
||||
|
||||
- `secret` is a string containing the secret for HMAC algorithms, or a function that should fetch the secret or public key as shown in the example with `jwks-rsa`.
|
||||
- `algorithms` (default: `HS256`)
|
||||
- `onAuthentication` is a function that will be called with the `decodedToken` as a parameter after the token is authenticated. Return a value to add to the `user` property in the socket object.
|
||||
|
||||
### Client side
|
||||
|
||||
@ -119,7 +146,7 @@ socket.on('messages', (data) => {
|
||||
|
||||
Anyone can help to improve the project, submit a Feature Request, a bug report or even correct a simple spelling mistake.
|
||||
|
||||
The steps to contribute can be found in the [CONTRIBUTING.md](./.github/CONTRIBUTING.md) file.
|
||||
The steps to contribute can be found in the [CONTRIBUTING.md](./CONTRIBUTING.md) file.
|
||||
|
||||
## 📄 License
|
||||
|
||||
|
24804
package-lock.json
generated
Normal file
24804
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
41
package.json
41
package.json
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@thream/socketio-jwt",
|
||||
"version": "2.0.0",
|
||||
"version": "2.1.0",
|
||||
"description": "Authenticate socket.io incoming connections with JWTs.",
|
||||
"license": "MIT",
|
||||
"main": "build/index.js",
|
||||
@ -60,23 +60,23 @@
|
||||
"coverageDirectory": "../coverage/"
|
||||
},
|
||||
"ts-standard": {
|
||||
"files": [
|
||||
"./src/**/*.ts"
|
||||
"ignore": [
|
||||
"build",
|
||||
"coverage",
|
||||
"node_modules"
|
||||
],
|
||||
"envs": [
|
||||
"node",
|
||||
"jest"
|
||||
]
|
||||
],
|
||||
"report": "stylish"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "rimraf ./build && tsc",
|
||||
"markdownlint": "markdownlint '**/*.md' --ignore node_modules",
|
||||
"lint": "ts-standard | snazzy",
|
||||
"format": "ts-standard --fix | snazzy",
|
||||
"markdownlint": "markdownlint '**/*.md' --dot --ignore node_modules",
|
||||
"lint": "ts-standard",
|
||||
"release": "release-it",
|
||||
"test": "jest",
|
||||
"test:watchAll": "jest --watchAll",
|
||||
"test:clearCache": "jest --clearCache",
|
||||
"postinstall": "husky install",
|
||||
"prepublishOnly": "pinst --disable",
|
||||
"postpublish": "pinst --enable"
|
||||
@ -88,28 +88,27 @@
|
||||
"jsonwebtoken": "8.5.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@commitlint/cli": "11.0.0",
|
||||
"@commitlint/config-conventional": "11.0.0",
|
||||
"@release-it/conventional-changelog": "2.0.0",
|
||||
"@commitlint/cli": "12.0.1",
|
||||
"@commitlint/config-conventional": "12.0.1",
|
||||
"@release-it/conventional-changelog": "2.0.1",
|
||||
"@types/express": "4.17.11",
|
||||
"@types/jest": "26.0.20",
|
||||
"@types/jsonwebtoken": "8.5.0",
|
||||
"@types/node": "14.14.31",
|
||||
"@types/node": "14.14.32",
|
||||
"@types/server-destroy": "1.0.1",
|
||||
"axios": "0.21.1",
|
||||
"express": "4.17.1",
|
||||
"husky": "5.1.0",
|
||||
"husky": "5.1.3",
|
||||
"jest": "26.6.3",
|
||||
"markdownlint-cli": "0.26.0",
|
||||
"pinst": "2.1.4",
|
||||
"markdownlint-cli": "0.27.1",
|
||||
"pinst": "2.1.6",
|
||||
"release-it": "14.4.1",
|
||||
"rimraf": "3.0.2",
|
||||
"server-destroy": "1.0.1",
|
||||
"snazzy": "9.0.0",
|
||||
"socket.io": "3.1.1",
|
||||
"socket.io-client": "3.1.1",
|
||||
"ts-jest": "26.5.1",
|
||||
"socket.io": "3.1.2",
|
||||
"socket.io-client": "3.1.2",
|
||||
"ts-jest": "26.5.3",
|
||||
"ts-standard": "10.0.0",
|
||||
"typescript": "4.1.5"
|
||||
"typescript": "4.2.3"
|
||||
}
|
||||
}
|
||||
|
@ -1,7 +1,7 @@
|
||||
import axios from 'axios'
|
||||
import { io } from 'socket.io-client'
|
||||
|
||||
import { fixtureStart, fixtureStop } from './fixture'
|
||||
import { fixtureStart, fixtureStop, getSocket, Profile } from './fixture'
|
||||
|
||||
describe('authorize - with secret as string in options', () => {
|
||||
let token: string = ''
|
||||
@ -101,3 +101,76 @@ describe('authorize - with secret as callback in options', () => {
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('authorize - with onAuthentication callback in options', () => {
|
||||
let token: string = ''
|
||||
let wrongToken: string = ''
|
||||
|
||||
beforeEach(async (done) => {
|
||||
jest.setTimeout(15_000)
|
||||
await fixtureStart(
|
||||
async () => {
|
||||
const response = await axios.post('http://localhost:9000/login')
|
||||
token = response.data.token
|
||||
const responseWrong = await axios.post('http://localhost:9000/login-wrong')
|
||||
wrongToken = responseWrong.data.token
|
||||
done()
|
||||
},
|
||||
{
|
||||
secret: secretCallback,
|
||||
onAuthentication: (decodedToken: Profile) => {
|
||||
if (!decodedToken.checkField) {
|
||||
throw new Error('Check Field validation failed')
|
||||
}
|
||||
return {
|
||||
email: decodedToken.email
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
afterEach((done) => {
|
||||
fixtureStop(done)
|
||||
})
|
||||
|
||||
it('should connect the user', (done) => {
|
||||
const socket = io('http://localhost:9000', {
|
||||
auth: { token: `Bearer ${token}` }
|
||||
})
|
||||
socket.on('connect', () => {
|
||||
socket.close()
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should contain user property', (done) => {
|
||||
const socketServer = getSocket()
|
||||
socketServer?.on('connection', (client: any) => {
|
||||
expect(client.user.email).toEqual('john@doe.com')
|
||||
})
|
||||
const socket = io('http://localhost:9000', {
|
||||
auth: { token: `Bearer ${token}` }
|
||||
})
|
||||
socket.on('connect', () => {
|
||||
socket.close()
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should emit error when user validation fails', (done) => {
|
||||
const socket = io('http://localhost:9000', {
|
||||
auth: { token: `Bearer ${wrongToken}` }
|
||||
})
|
||||
socket.on('connect_error', (err: any) => {
|
||||
try {
|
||||
expect(err.message).toEqual('Check Field validation failed')
|
||||
} catch (err) {
|
||||
socket.close()
|
||||
done(err)
|
||||
}
|
||||
socket.close()
|
||||
done()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
@ -7,6 +7,12 @@ import enableDestroy from 'server-destroy'
|
||||
|
||||
import { authorize, AuthorizeOptions } from '../../index'
|
||||
|
||||
export interface Profile {
|
||||
email: string
|
||||
id: number
|
||||
checkField: boolean
|
||||
}
|
||||
|
||||
interface Socket {
|
||||
io: null | SocketIoServer
|
||||
init: (httpServer: HttpServer | HttpsServer) => void
|
||||
@ -34,9 +40,21 @@ export const fixtureStart = async (
|
||||
keySecret = await options.secret({ header: { alg: 'RS256' }, payload: '' })
|
||||
}
|
||||
app.post('/login', (_req, res) => {
|
||||
const profile = {
|
||||
const profile: Profile = {
|
||||
email: 'john@doe.com',
|
||||
id: 123
|
||||
id: 123,
|
||||
checkField: true
|
||||
}
|
||||
const token = jwt.sign(profile, keySecret, {
|
||||
expiresIn: 60 * 60 * 5
|
||||
})
|
||||
return res.json({ token })
|
||||
})
|
||||
app.post('/login-wrong', (_req, res) => {
|
||||
const profile: Profile = {
|
||||
email: 'john@doe.com',
|
||||
id: 123,
|
||||
checkField: false
|
||||
}
|
||||
const token = jwt.sign(profile, keySecret, {
|
||||
expiresIn: 60 * 60 * 5
|
||||
@ -56,3 +74,7 @@ export const fixtureStop = (callback: Function): void => {
|
||||
} catch (err) {}
|
||||
callback()
|
||||
}
|
||||
|
||||
export const getSocket = (): SocketIoServer | null => {
|
||||
return socket.io
|
||||
}
|
||||
|
@ -14,6 +14,7 @@ interface ExtendedError extends Error {
|
||||
interface ExtendedSocket {
|
||||
encodedToken?: string
|
||||
decodedToken?: any
|
||||
user?: any
|
||||
}
|
||||
|
||||
type SocketIOMiddleware = (
|
||||
@ -34,10 +35,11 @@ type SecretCallback = (decodedToken: CompleteDecodedToken) => Promise<string>
|
||||
export interface AuthorizeOptions {
|
||||
secret: string | SecretCallback
|
||||
algorithms?: Algorithm[]
|
||||
onAuthentication?: (decodedToken: any) => Promise<any> | any
|
||||
}
|
||||
|
||||
export const authorize = (options: AuthorizeOptions): SocketIOMiddleware => {
|
||||
const { secret, algorithms = ['HS256'] } = options
|
||||
const { secret, algorithms = ['HS256'], onAuthentication } = options
|
||||
return async (socket, next) => {
|
||||
let encodedToken: string | null = null
|
||||
const { token } = socket.handshake.auth
|
||||
@ -78,6 +80,13 @@ export const authorize = (options: AuthorizeOptions): SocketIOMiddleware => {
|
||||
)
|
||||
}
|
||||
socket.decodedToken = decodedToken
|
||||
if (onAuthentication != null) {
|
||||
try {
|
||||
socket.user = await onAuthentication(decodedToken)
|
||||
} catch (err) {
|
||||
return next(err)
|
||||
}
|
||||
}
|
||||
return next()
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user