import jwt , { SigningKeyCallback , JwtHeader } from 'jsonwebtoken' ; import jwksClient from 'jwks-rsa' ; import * as msal from '@azure/msal-node' ; const keyClient = jwksClient ( { jwksUri : 'https://login.microsoftonline.com/common/discovery/keys' } ) ; param { JwtHeader } header param { SigningKeyCallback } callback function getSigningKey ( header , callback ) { if ( header ) { keyClient . getSigningKey ( header . kid ! , ( err , key ) => { if ( err ) { callback ( err , undefined ) ; } else { callback ( null , key . getPublicKey ( ) ) ; } } ) ; } } param { string } authHeader returns { Promise < string | null > } async function validateJwt ( authHeader ) { return new Promise ( ( resolve , reject ) => { const token = authHeader . split ( ' ' ) [ 1 ] ; const validationOptions = { audience : process . env . PROXY_APP_ID , } ; jwt . verify ( token , getSigningKey , validationOptions , ( err , payload ) => { if ( err ) { resolve ( null ) ; } resolve ( token ) ; } ) ; } ) ; } param authHeader returns { Promise < string | null > } export default async function getAccessTokenOnBehalfOf ( authHeader ) { const token = await validateJwt ( authHeader ) ; if ( token ) { const msalClient = new msal . ConfidentialClientApplication ( { auth : { clientId : process . env . PROXY_APP_ID ! , clientSecret : process . env . PROXY_APP_SECRET } } ) ; try { const result = await msalClient . acquireTokenOnBehalfOf ( { oboAssertion : token , skipCache : true , scopes : [ 'https://graph.microsoft.com/.default' ] } ) ; return result ? result . accessToken : null ; } catch ( error ) { console . log ( `Token error: ${ error }` ) ; return null ; } } else { return null ; } }