2
1
mirror of https://github.com/Thream/socketio-jwt.git synced 2024-07-21 09:38:31 +02:00

feat: add algorithms option

This commit is contained in:
divlo 2020-12-30 14:50:56 +01:00
parent 92d1ecd7e0
commit abbabc588e

View File

@ -1,4 +1,4 @@
import jwt from 'jsonwebtoken' import jwt, { Algorithm } from 'jsonwebtoken'
import { Socket } from 'socket.io' import { Socket } from 'socket.io'
import { UnauthorizedError } from './UnauthorizedError' import { UnauthorizedError } from './UnauthorizedError'
@ -14,10 +14,11 @@ type SocketIOMiddleware = (
interface AuthorizeOptions { interface AuthorizeOptions {
secret: string secret: string
algorithms?: Algorithm[]
} }
export const authorize = (options: AuthorizeOptions): SocketIOMiddleware => { export const authorize = (options: AuthorizeOptions): SocketIOMiddleware => {
const { secret } = options const { secret, algorithms = ['HS256'] } = options
return (socket, next) => { return (socket, next) => {
let token: string | null = null let token: string | null = null
const authorizationHeader = socket.request.headers.authorization const authorizationHeader = socket.request.headers.authorization
@ -43,7 +44,7 @@ export const authorize = (options: AuthorizeOptions): SocketIOMiddleware => {
socket = Object.assign(socket, { encodedToken: token }) socket = Object.assign(socket, { encodedToken: token })
let payload: any let payload: any
try { try {
payload = jwt.verify(token, secret) payload = jwt.verify(token, secret, { algorithms })
} catch { } catch {
return next( return next(
new UnauthorizedError('invalid_token', { new UnauthorizedError('invalid_token', {