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

69 lines
1.7 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
interface AuthorizeOptions {
secret: string
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
2020-12-29 04:05:39 +01:00
return (socket, next) => {
let token: string | null = null
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]'
})
)
}
token = tokenSplitted[1]
}
if (token == null) {
return next(
new UnauthorizedError('credentials_required', {
message: 'no token provided'
})
)
}
// Store encoded JWT
socket.encodedToken = token
2020-12-29 04:05:39 +01:00
let payload: any
try {
2020-12-30 14:50:56 +01:00
payload = jwt.verify(token, secret, { 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
socket.decodedToken = payload
2020-12-29 04:05:39 +01:00
return next()
}
}