import { request } from './../config' ; import * as url from 'url' ; import template = require ( 'lodash.template' ) ; const xmldoc = require ( 'xmldoc' ) ; import { IAdfsUserCredentials } from './../auth/IAuthOptions' ; import { SamlAssertion } from './SamlAssertion' ; import { template as adfsSamlWsfedTemplate } from './../templates/AdfsSamlWsfed' ; export class AdfsHelper { public static getSamlAssertion ( credentials ) { const adfsHost = url . parse ( credentials . adfsUrl ) . host ; const usernameMixedUrl = `https://${ adfsHost }/adfs/services/trust/13/usernamemixed` ; const samlBody = template ( adfsSamlWsfedTemplate ) ( { to : usernameMixedUrl , username : credentials . username , password : credentials . password , relyingParty : credentials . relyingParty } ) ; return request . post ( usernameMixedUrl , { body : samlBody , resolveBodyOnly : true , headers : { 'Content-Length' : samlBody . length . toString ( ) , 'Content-Type' : 'application/soap+xml; charset=utf-8' } } ) . then ( xmlResponse => { const doc = new xmldoc . XmlDocument ( xmlResponse ) ; const tokenResponseCollection = doc . childNamed ( 's:Body' ) . firstChild ; if ( tokenResponseCollection . name . indexOf ( 'Fault' ) !== - 1 ) { throw new Error ( tokenResponseCollection . toString ( ) ) ; } const responseNamespace = tokenResponseCollection . name . split ( ':' ) [ 0 ] ; const securityTokenResponse = doc . childNamed ( 's:Body' ) . firstChild . firstChild ; const samlAssertion = securityTokenResponse . childNamed ( responseNamespace + ':RequestedSecurityToken' ) . firstChild ; const notBefore = samlAssertion . firstChild . attr [ 'NotBefore' ] ; const notAfter = samlAssertion . firstChild . attr [ 'NotOnOrAfter' ] ; return { value : samlAssertion . toString ( { compressed : true } ) , notAfter : notAfter , notBefore : notBefore } as SamlAssertion ; } ) ; } }