This repository has been archived on 2024-11-11. You can view files and clone it, but cannot push or open issues or pull requests.
socketio-jwt/src/authorize.ts

78 lines
2.1 KiB
TypeScript
Raw Normal View History

2020-12-30 14:50:56 +01:00
import jwt, { Algorithm } from 'jsonwebtoken'
2020-12-29 04:05:39 +01:00
import { Socket } from 'socket.io'
import { UnauthorizedError } from './UnauthorizedError'
declare module 'socket.io' {
interface Socket extends ExtendedSocket {}
}
2020-12-29 04:05:39 +01:00
interface ExtendedError extends Error {
data?: any
}
interface ExtendedSocket {
encodedToken?: string
decodedToken?: any
}
2020-12-29 04:05:39 +01:00
type SocketIOMiddleware = (
socket: Socket,
next: (err?: ExtendedError) => void
) => void
2021-01-07 14:30:37 +01:00
type SecretCallback = (decodedToken: null | { [key: string]: any } | string) => Promise<string>
export interface AuthorizeOptions {
secret: string | SecretCallback
2020-12-30 14:50:56 +01:00
algorithms?: Algorithm[]
2020-12-29 04:05:39 +01:00
}
export const authorize = (options: AuthorizeOptions): SocketIOMiddleware => {
2020-12-30 14:50:56 +01:00
const { secret, algorithms = ['HS256'] } = options
2021-01-07 14:30:37 +01:00
return async (socket, next) => {
let encodedToken: string | null = null
2020-12-29 04:05:39 +01:00
const authorizationHeader = socket.request.headers.authorization
if (authorizationHeader != null) {
const tokenSplitted = authorizationHeader.split(' ')
if (tokenSplitted.length !== 2 || tokenSplitted[0] !== 'Bearer') {
return next(
new UnauthorizedError('credentials_bad_format', {
message: 'Format is Authorization: Bearer [token]'
})
)
}
2021-01-07 14:30:37 +01:00
encodedToken = tokenSplitted[1]
2020-12-29 04:05:39 +01:00
}
2021-01-07 14:30:37 +01:00
if (encodedToken == null) {
2020-12-29 04:05:39 +01:00
return next(
new UnauthorizedError('credentials_required', {
message: 'no token provided'
})
)
}
// Store encoded JWT
2021-01-07 14:30:37 +01:00
socket.encodedToken = encodedToken
let keySecret: string | null = null
let decodedToken: any
if (typeof secret === 'string') {
keySecret = secret
} else {
decodedToken = jwt.decode(encodedToken, { complete: true })
keySecret = await secret(decodedToken)
}
2020-12-29 04:05:39 +01:00
try {
2021-01-07 14:30:37 +01:00
decodedToken = jwt.verify(encodedToken, keySecret, { algorithms })
2020-12-29 04:05:39 +01:00
} catch {
return next(
new UnauthorizedError('invalid_token', {
message: 'Unauthorized: Token is missing or invalid Bearer'
})
)
}
// Store decoded JWT
2021-01-07 14:30:37 +01:00
socket.decodedToken = decodedToken
2020-12-29 04:05:39 +01:00
return next()
}
}