-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathazureTokenValidation.js
More file actions
54 lines (50 loc) · 1.77 KB
/
azureTokenValidation.js
File metadata and controls
54 lines (50 loc) · 1.77 KB
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
// Run this by calling ```node tokenValidation.js``` in the console
const jwt = require('jsonwebtoken')
const fetch = require('node-fetch')
var forge = require('node-forge')
class AzureTokenValidation {
/**
* @param {String} idToken The Azure ID token to validate
*/
async validate(idToken) {
try {
const kid = this.getKid(idToken)
const publicKey = await this.getPublicKey(kid)
const t = jwt.verify(idToken, publicKey, { algorithms: ['RS256'] })
return t
} catch(exception) {
return false
}
}
/**
* @param {String} idToken The Azure ID token to get kid from
*/
getKid(idToken) {
const decodedJwt = jwt.decode(idToken, {complete: true})
return decodedJwt.header.kid
}
/**
* @param {Object} fetchSigningKeyInformation Keys from fetchSigningKeyInformation
* @param {String} kid
*/
async getPublicKey(kid) {
const signingKeys = await this.fetchSigningKeyInformation()
const key = signingKeys.keys.find(k => k.kid === kid)
// console.log(key)
const msPublicKey = key.x5c[0]
const PEMSTART = "-----BEGIN CERTIFICATE-----\n"
const PEMEND = "\n-----END CERTIFICATE-----\n"
const pem = PEMSTART + msPublicKey + PEMEND
const certificate = forge.pki.certificateFromPem(pem)
return forge.pki.publicKeyToPem(certificate.publicKey)
}
/**
* Fetch public signing key information from Microsoft
*/
async fetchSigningKeyInformation() {
const urlKeys = 'https://login.microsoftonline.com/common/discovery/v2.0/keys'
const keys = await fetch(urlKeys, { method: "Get" })
const jsonKeys = await keys.json()
return jsonKeys
}
}