-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
76 lines (71 loc) · 2.5 KB
/
index.js
File metadata and controls
76 lines (71 loc) · 2.5 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
const pfxToPem = require('./lib/pfx-to-pem')
const msal = require('@azure/msal-node')
/**
* Gets a token for sharepoint rest api
*
* @param {object} options
* @param {string} [options.pfxcert] PFX-cert as base64
* @param {string} [options.pemcert] PEM-cert as base64
* @param {string} [options.pemprivateKey] private key PEM as base64
* @param {string} [options.privateKeyPassphrase] privateKey for decrypting cert-key
* @param {string} options.thumbprint can be obtained from app registration, or inspecting cert
* @param {string} options.clientId app reg client id
* @param {string} options.tenantId
* @param {string} options.tenantName
*
* @return {object} accessToken
*/
module.exports = async options => {
if (!options) {
throw Error('Missing required input: options')
}
if (!options.pemcert && !options.pfxcert) {
throw Error('Missing required input: options.pemcert or options.pfxcert')
}
if (options.pemcert && !options.pemprivateKey) {
throw Error('Missing required input: options.pemprivateKey')
}
if (!options.thumbprint) {
throw Error('Missing required input: options.thumbprint')
}
if (!options.clientId) {
throw Error('Missing required input: options.clientId')
}
if (!options.tenantId) {
throw Error('Missing required input: options.tenantId')
}
if (!options.tenantName) {
throw Error('Missing required input: options.tenantName')
}
const certificate = {
cert: '',
key: ''
}
if (options.pfxcert) {
// Må konverte internt her
const cert = pfxToPem(options.pfxcert, options.privateKeyPassphrase || null)
certificate.cert = cert.certificate
certificate.key = cert.key
} else {
// bare sett det til det som er sendt inn
certificate.cert = Buffer.from(options.pemcert, 'base64').toString()
certificate.key = Buffer.from(options.pemprivateKey, 'base64').toString()
}
const authConfig = {
auth: {
clientId: options.clientId,
authority: `https://login.microsoftonline.com/${options.tenantId}/`,
clientCertificate: {
thumbprint: options.thumbprint, // can be obtained when uploading certificate to Azure AD (or inspect the certificate properties)
privateKey: certificate.key
}
}
}
// Create msal application object
const cca = new msal.ConfidentialClientApplication(authConfig)
const clientCredentials = {
scopes: [`https://${options.tenantName}.sharepoint.com/.default`]
}
const token = await cca.acquireTokenByClientCredential(clientCredentials)
return token
}