forked from lmammino/jwt-cracker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjwtValidator.js
67 lines (53 loc) · 1.6 KB
/
jwtValidator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
export default class JWTValidator {
static SUPPORTED_ALGORITHM = [
'HS256',
'HS384',
'HS512'
]
static decodeHeader (token) {
const parts = token.split('.')
try {
const decodedHeader = JSON.parse(Buffer.from(parts[0], 'base64').toString('utf-8'))
return decodedHeader
} catch (e) {
console.log('Invalid token format. Invalid header.')
return null
}
}
static validateToken (token) {
const isTokenValid = this.validateGeneralJwtFormat(token) && this.validateHmacAlgorithmHeader(token)
const algorithm = isTokenValid ? this.decodeHeader(token).alg : ''
return { isTokenValid, algorithm }
}
static validateGeneralJwtFormat (token) {
if (token.length === 0) {
console.log('Missing token')
return false
}
const parts = token.split('.')
if (parts.length !== 3) {
console.log('Invalid token format. Invalid number of parts.')
return false
}
if (!parts.every(part => part.length > 0)) {
console.log('Invalid token format. Parts should not be empty.')
return false
}
return true
}
static validateHmacAlgorithmHeader (token) {
const decodedHeader = this.decodeHeader(token)
if (!decodedHeader) {
return false
}
if (decodedHeader.typ !== 'JWT') {
console.log(`Unsupported Typ: ${decodedHeader.typ}`)
return false
}
if (!this.SUPPORTED_ALGORITHM.includes(decodedHeader.alg)) {
console.log(`Unsupported algorithm: ${decodedHeader.alg}. Only ${this.SUPPORTED_ALGORITHM.join(', ')} are supported.`)
return false
}
return true
}
}