2 * Licensed to the University Corporation for Advanced Internet
3 * Development, Inc. (UCAID) under one or more contributor license
4 * agreements. See the NOTICE file distributed with this work for
5 * additional information regarding copyright ownership.
7 * UCAID licenses this file to you under the Apache License,
8 * Version 2.0 (the "License"); you may not use this file except
9 * in compliance with the License. You may obtain a copy of the
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17 * either express or implied. See the License for the specific
18 * language governing permissions and limitations under the License.
22 * SAML2SessionInitiator.cpp
24 * SAML 2.0 AuthnRequest support.
28 #include "Application.h"
29 #include "exceptions.h"
30 #include "ServiceProvider.h"
31 #include "handler/AbstractHandler.h"
32 #include "handler/RemotedHandler.h"
33 #include "handler/SessionInitiator.h"
34 #include "util/SPConstants.h"
37 # include "metadata/MetadataProviderCriteria.h"
38 # include <saml/SAMLConfig.h>
39 # include <saml/saml2/core/Protocols.h>
40 # include <saml/saml2/metadata/EndpointManager.h>
41 # include <saml/saml2/metadata/Metadata.h>
42 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
43 # include <saml/util/SAMLConstants.h>
44 using namespace opensaml::saml2;
45 using namespace opensaml::saml2p;
46 using namespace opensaml::saml2md;
48 # include "lite/SAMLConstants.h"
49 # include <xercesc/util/XMLUniDefs.hpp>
52 using namespace shibsp;
53 using namespace opensaml;
54 using namespace xmltooling;
59 #if defined (_MSC_VER)
60 #pragma warning( push )
61 #pragma warning( disable : 4250 )
64 class SHIBSP_DLLLOCAL SAML2SessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
67 SAML2SessionInitiator(const DOMElement* e, const char* appId);
68 virtual ~SAML2SessionInitiator() {
70 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
71 XMLString::release(&m_outgoing);
72 for_each(m_encoders.begin(), m_encoders.end(), cleanup_pair<const XMLCh*,MessageEncoder>());
73 delete m_requestTemplate;
79 void init(const char* location); // encapsulates actions that need to run either in the c'tor or setParent
81 void setParent(const PropertySet* parent);
82 void receive(DDF& in, ostream& out);
83 pair<bool,long> unwrap(SPRequest& request, DDF& out) const;
84 pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
86 const XMLCh* getProtocolFamily() const {
87 return samlconstants::SAML20P_NS;
91 pair<bool,long> doRequest(
92 const Application& application,
93 const HTTPRequest* httpRequest,
94 HTTPResponse& httpResponse,
96 const XMLCh* acsIndex,
98 const char* acsLocation,
99 const XMLCh* acsBinding,
102 const char* authnContextClassRef,
103 const char* authnContextComparison,
104 const char* NameIDFormat,
105 const char* SPNameQualifier,
110 auto_ptr_char m_paosNS,m_ecpNS;
111 auto_ptr_XMLCh m_paosBinding;
114 vector<const XMLCh*> m_bindings;
115 map<const XMLCh*,MessageEncoder*> m_encoders;
116 MessageEncoder* m_ecp;
117 AuthnRequest* m_requestTemplate;
123 #if defined (_MSC_VER)
124 #pragma warning( pop )
127 SessionInitiator* SHIBSP_DLLLOCAL SAML2SessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
129 return new SAML2SessionInitiator(p.first, p.second);
134 SAML2SessionInitiator::SAML2SessionInitiator(const DOMElement* e, const char* appId)
135 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.SAML2"), nullptr, &m_remapper), m_appId(appId),
136 m_paosNS(samlconstants::PAOS_NS), m_ecpNS(samlconstants::SAML20ECP_NS), m_paosBinding(samlconstants::SAML20_BINDING_PAOS),
138 m_outgoing(nullptr), m_ecp(nullptr), m_requestTemplate(nullptr)
144 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
145 // Check for a template AuthnRequest to build from.
146 DOMElement* child = XMLHelper::getFirstChildElement(e, samlconstants::SAML20P_NS, AuthnRequest::LOCAL_NAME);
148 m_requestTemplate = dynamic_cast<AuthnRequest*>(AuthnRequestBuilder::buildOneFromElement(child));
152 // If Location isn't set, defer initialization until the setParent call.
153 pair<bool,const char*> loc = getString("Location");
158 m_supportedOptions.insert("isPassive");
161 void SAML2SessionInitiator::setParent(const PropertySet* parent)
163 DOMPropertySet::setParent(parent);
164 pair<bool,const char*> loc = getString("Location");
168 void SAML2SessionInitiator::init(const char* location)
171 string address = m_appId + location + "::run::SAML2SI";
172 setAddress(address.c_str());
175 m_log.warn("no Location property in SAML2 SessionInitiator (or parent), can't register as remoted handler");
178 pair<bool,bool> flag = getBool("ECP");
180 m_ecp = flag.first && flag.second;
185 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
186 // If directed, build an ECP encoder.
187 if (flag.first && flag.second) {
189 m_ecp = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
190 samlconstants::SAML20_BINDING_PAOS, pair<const DOMElement*,const XMLCh*>(getElement(), nullptr)
193 catch (exception& ex) {
194 m_log.error("error building PAOS/ECP MessageEncoder: %s", ex.what());
198 // Handle outgoing binding setup.
199 pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings");
200 if (outgoing.first) {
201 m_outgoing = XMLString::replicate(outgoing.second);
202 XMLString::trim(m_outgoing);
205 // No override, so we'll install a default binding precedence.
206 string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
207 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
208 m_outgoing = XMLString::transcode(prec.c_str());
212 XMLCh* start = m_outgoing;
213 while (start && *start) {
214 pos = XMLString::indexOf(start,chSpace);
216 *(start + pos)=chNull;
217 m_bindings.push_back(start);
219 auto_ptr_char b(start);
220 MessageEncoder * encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
221 b.get(),pair<const DOMElement*,const XMLCh*>(getElement(), nullptr)
223 if (encoder->isUserAgentPresent() && XMLString::equals(getProtocolFamily(), encoder->getProtocolFamily())) {
224 m_encoders[start] = encoder;
225 m_log.debug("supporting outgoing binding (%s)", b.get());
229 m_log.warn("skipping outgoing binding (%s), not a SAML 2.0 front-channel mechanism", b.get());
232 catch (exception& ex) {
233 m_log.error("error building MessageEncoder: %s", ex.what());
236 start = start + pos + 1;
244 pair<bool,long> SAML2SessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
246 // First check for ECP support, since that doesn't require an IdP to be known.
248 if (m_ecp && request.getHeader("Accept").find("application/vnd.paos+xml") != string::npos) {
249 string PAOS = request.getHeader("PAOS");
250 if (PAOS.find(m_paosNS.get()) != string::npos && PAOS.find(m_ecpNS.get()) != string::npos)
254 // We have to know the IdP to function unless this is ECP.
255 if ((!ECP && entityID.empty()) || !checkCompatibility(request, isHandler))
256 return make_pair(false,0L);
259 pair<bool,const char*> prop;
260 const Handler* ACS=nullptr;
261 pair<bool,const char*> acClass, acComp, nidFormat, spQual;
262 bool isPassive=false,forceAuthn=false;
263 const Application& app=request.getApplication();
265 // ECP means the ACS will be by value no matter what.
266 pair<bool,bool> acsByIndex = ECP ? make_pair(true,false) : getBool("acsByIndex");
269 prop.second = request.getParameter("acsIndex");
270 if (prop.second && *prop.second) {
271 ACS = app.getAssertionConsumerServiceByIndex(atoi(prop.second));
273 request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using acsIndex property");
274 else if (ECP && !XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_PAOS)) {
275 request.log(SPRequest::SPWarn, "acsIndex in request referenced a non-PAOS ACS, using default ACS location");
280 prop = getString("target", request);
282 target = prop.second;
284 // Always need to recover target URL to compute handler below.
285 recoverRelayState(app, request, request, target, false);
286 limitRelayState(m_log, app, request, target.c_str());
288 pair<bool,bool> flag = getBool("isPassive", request);
289 isPassive = (flag.first && flag.second);
292 flag = getBool("forceAuthn", request);
293 forceAuthn = (flag.first && flag.second);
296 // Populate via parameter, map, or property.
297 acClass = getString("authnContextClassRef", request);
298 acComp = getString("authnContextComparison", request);
299 nidFormat = getString("NameIDFormat", request);
300 spQual = getString("SPNameQualifier", request);
303 // Check for a hardwired target value in the map or handler.
304 prop = getString("target", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
306 target = prop.second;
308 target = request.getRequestURL();
310 pair<bool,bool> flag = getBool("isPassive", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
311 isPassive = flag.first && flag.second;
313 flag = getBool("forceAuthn", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
314 forceAuthn = flag.first && flag.second;
317 // Populate via map or property.
318 acClass = getString("authnContextClassRef", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
319 acComp = getString("authnContextComparison", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
320 nidFormat = getString("NameIDFormat", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
321 spQual = getString("SPNameQualifier", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
325 m_log.debug("attempting to initiate session using SAML 2.0 Enhanced Client Profile");
327 m_log.debug("attempting to initiate session using SAML 2.0 with provider (%s)", entityID.c_str());
331 ACS = app.getAssertionConsumerServiceByProtocol(getProtocolFamily(), samlconstants::SAML20_BINDING_PAOS);
333 throw ConfigurationException("Unable to locate PAOS response endpoint.");
336 // Try fixed index property.
337 pair<bool,unsigned int> index = getUnsignedInt("acsIndex", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
339 ACS = app.getAssertionConsumerServiceByIndex(index.second);
343 // If we picked by index, validate the ACS for use with this protocol.
344 if (!ECP && (!ACS || !XMLString::equals(getProtocolFamily(), ACS->getProtocolFamily()))) {
346 request.log(SPRequest::SPWarn, "invalid acsIndex property, or non-SAML 2.0 ACS, using default SAML 2.0 ACS");
347 ACS = app.getAssertionConsumerServiceByProtocol(getProtocolFamily());
349 throw ConfigurationException("Unable to locate a SAML 2.0 ACS endpoint to use for response.");
352 // To invoke the request builder, the key requirement is to figure out how
353 // to express the ACS, by index or value, and if by value, where.
354 // We have to compute the handlerURL no matter what, because we may need to
355 // flip the index to an SSL-version.
356 string ACSloc = request.getHandlerURL(target.c_str());
358 SPConfig& conf = SPConfig::getConfig();
359 if (conf.isEnabled(SPConfig::OutOfProcess)) {
360 if (acsByIndex.first && acsByIndex.second) {
363 // We may already have RelayState set if we looped back here,
364 // but we've turned it back into a resource by this point, so if there's
365 // a target on the URL, reset to that value.
366 prop.second = request.getParameter("target");
367 if (prop.second && *prop.second)
368 target = prop.second;
371 // Determine index to use.
372 pair<bool,const XMLCh*> ix = pair<bool,const XMLCh*>(false,nullptr);
373 if (!strncmp(ACSloc.c_str(), "https", 5)) {
374 ix = ACS->getXMLString("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
376 ix = ACS->getXMLString("index");
379 ix = ACS->getXMLString("index");
383 app, &request, request, entityID.c_str(),
385 XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT),
387 isPassive, forceAuthn,
388 acClass.first ? acClass.second : nullptr,
389 acComp.first ? acComp.second : nullptr,
390 nidFormat.first ? nidFormat.second : nullptr,
391 spQual.first ? spQual.second : nullptr,
396 // Since we're not passing by index, we need to fully compute the return URL and binding.
397 // Compute the ACS URL. We add the ACS location to the base handlerURL.
398 prop = ACS->getString("Location");
400 ACSloc += prop.second;
403 // We may already have RelayState set if we looped back here,
404 // but we've turned it back into a resource by this point, so if there's
405 // a target on the URL, reset to that value.
406 prop.second = request.getParameter("target");
407 if (prop.second && *prop.second)
408 target = prop.second;
412 app, &request, request, entityID.c_str(),
414 XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT),
415 ACSloc.c_str(), ACS->getXMLString("Binding").second,
416 isPassive, forceAuthn,
417 acClass.first ? acClass.second : nullptr,
418 acComp.first ? acComp.second : nullptr,
419 nidFormat.first ? nidFormat.second : nullptr,
420 spQual.first ? spQual.second : nullptr,
426 DDF out,in = DDF(m_address.c_str()).structure();
427 DDFJanitor jin(in), jout(out);
428 in.addmember("application_id").string(app.getId());
429 if (!entityID.empty())
430 in.addmember("entity_id").string(entityID.c_str());
432 in.addmember("isPassive").integer(1);
434 in.addmember("forceAuthn").integer(1);
436 in.addmember("authnContextClassRef").string(acClass.second);
438 in.addmember("authnContextComparison").string(acComp.second);
440 in.addmember("NameIDFormat").string(nidFormat.second);
442 in.addmember("SPNameQualifier").string(spQual.second);
443 if (acsByIndex.first && acsByIndex.second) {
444 // Determine index to use.
445 pair<bool,const char*> ix = pair<bool,const char*>(false,nullptr);
446 if (!strncmp(ACSloc.c_str(), "https", 5)) {
447 ix = ACS->getString("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
449 ix = ACS->getString("index");
452 ix = ACS->getString("index");
454 in.addmember("acsIndex").string(ix.second);
455 if (XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT))
456 in.addmember("artifact").integer(1);
459 // Since we're not passing by index, we need to fully compute the return URL and binding.
460 // Compute the ACS URL. We add the ACS location to the base handlerURL.
461 prop = ACS->getString("Location");
463 ACSloc += prop.second;
464 in.addmember("acsLocation").string(ACSloc.c_str());
465 prop = ACS->getString("Binding");
466 in.addmember("acsBinding").string(prop.second);
467 if (XMLString::equals(prop.second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT))
468 in.addmember("artifact").integer(1);
472 // We may already have RelayState set if we looped back here,
473 // but we've turned it back into a resource by this point, so if there's
474 // a target on the URL, reset to that value.
475 prop.second = request.getParameter("target");
476 if (prop.second && *prop.second)
477 target = prop.second;
480 in.addmember("RelayState").unsafe_string(target.c_str());
482 // Remote the processing.
483 out = request.getServiceProvider().getListenerService()->send(in);
484 return unwrap(request, out);
487 pair<bool,long> SAML2SessionInitiator::unwrap(SPRequest& request, DDF& out) const
489 // See if there's any response to send back.
490 if (!out["redirect"].isnull() || !out["response"].isnull()) {
491 // If so, we're responsible for handling the POST data, probably by dropping a cookie.
492 preservePostData(request.getApplication(), request, request, out["RelayState"].string());
494 return RemotedHandler::unwrap(request, out);
497 void SAML2SessionInitiator::receive(DDF& in, ostream& out)
500 const char* aid=in["application_id"].string();
501 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
503 // Something's horribly wrong.
504 m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
505 throw ConfigurationException("Unable to locate application for new session, deleted?");
509 DDFJanitor jout(ret);
511 // Wrap the outgoing object with a Response facade.
512 auto_ptr<HTTPResponse> http(getResponse(ret));
514 auto_ptr_XMLCh index(in["acsIndex"].string());
515 auto_ptr_XMLCh bind(in["acsBinding"].string());
517 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
518 string postData(in["PostData"].string() ? in["PostData"].string() : "");
520 // Since we're remoted, the result should either be a throw, which we pass on,
521 // a false/0 return, which we just return as an empty structure, or a response/redirect,
522 // which we capture in the facade and send back.
524 *app, nullptr, *http.get(), in["entity_id"].string(),
526 (in["artifact"].integer() != 0),
527 in["acsLocation"].string(), bind.get(),
528 in["isPassive"].integer()==1, in["forceAuthn"].integer()==1,
529 in["authnContextClassRef"].string(), in["authnContextComparison"].string(),
530 in["NameIDFormat"].string(), in["SPNameQualifier"].string(),
535 ret.addmember("RelayState").unsafe_string(relayState.c_str());
541 class _sameIdP : public binary_function<const IDPEntry*, const XMLCh*, bool>
544 bool operator()(const IDPEntry* entry, const XMLCh* entityID) const {
545 return entry ? XMLString::equals(entry->getProviderID(), entityID) : false;
551 pair<bool,long> SAML2SessionInitiator::doRequest(
552 const Application& app,
553 const HTTPRequest* httpRequest,
554 HTTPResponse& httpResponse,
555 const char* entityID,
556 const XMLCh* acsIndex,
557 bool artifactInbound,
558 const char* acsLocation,
559 const XMLCh* acsBinding,
562 const char* authnContextClassRef,
563 const char* authnContextComparison,
564 const char* NameIDFormat,
565 const char* SPNameQualifier,
570 bool ECP = XMLString::equals(acsBinding, m_paosBinding.get());
572 pair<const EntityDescriptor*,const RoleDescriptor*> entity = pair<const EntityDescriptor*,const RoleDescriptor*>(nullptr,nullptr);
573 const IDPSSODescriptor* role = nullptr;
574 const EndpointType* ep = nullptr;
575 const MessageEncoder* encoder = nullptr;
577 // We won't need this for ECP, but safety dictates we get the lock here.
578 MetadataProvider* m=app.getMetadataProvider();
584 m_log.error("MessageEncoder for PAOS binding not available");
585 return make_pair(false,0L);
589 // Use metadata to locate the IdP's SSO service.
590 MetadataProviderCriteria mc(app, entityID, &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
591 entity=m->getEntityDescriptor(mc);
593 m_log.warn("unable to locate metadata for provider (%s)", entityID);
594 throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
596 else if (!entity.second) {
597 m_log.log(getParent() ? Priority::INFO : Priority::WARN, "unable to locate SAML 2.0 identity provider role for provider (%s)", entityID);
599 return make_pair(false,0L);
600 throw MetadataException("Unable to locate SAML 2.0 identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
602 else if (artifactInbound && !SPConfig::getConfig().getArtifactResolver()->isSupported(dynamic_cast<const SSODescriptorType&>(*entity.second))) {
603 m_log.warn("artifact binding selected for response, but identity provider lacks support");
605 return make_pair(false,0L);
606 throw MetadataException("Identity provider ($entityID) lacks SAML 2.0 artifact support.", namedparams(1, "entityID", entityID));
609 // Loop over the supportable outgoing bindings.
610 role = dynamic_cast<const IDPSSODescriptor*>(entity.second);
611 vector<const XMLCh*>::const_iterator b;
612 for (b = m_bindings.begin(); b!=m_bindings.end(); ++b) {
613 if (ep=EndpointManager<SingleSignOnService>(role->getSingleSignOnServices()).getByBinding(*b)) {
614 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
615 if (enc!=m_encoders.end())
616 encoder = enc->second;
620 if (!ep || !encoder) {
621 m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
623 return make_pair(false,0L);
624 throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
628 preserveRelayState(app, httpResponse, relayState);
630 auto_ptr<AuthnRequest> req(m_requestTemplate ? m_requestTemplate->cloneAuthnRequest() : AuthnRequestBuilder::buildAuthnRequest());
631 if (m_requestTemplate) {
632 // Freshen TS and ID.
634 req->setIssueInstant(time(nullptr));
638 req->setDestination(ep->getLocation());
639 if (acsIndex && *acsIndex)
640 req->setAssertionConsumerServiceIndex(acsIndex);
642 auto_ptr_XMLCh wideloc(acsLocation);
643 req->setAssertionConsumerServiceURL(wideloc.get());
645 if (acsBinding && *acsBinding)
646 req->setProtocolBinding(acsBinding);
648 req->IsPassive(isPassive);
650 req->ForceAuthn(forceAuthn);
651 if (!req->getIssuer()) {
652 Issuer* issuer = IssuerBuilder::buildIssuer();
653 req->setIssuer(issuer);
654 issuer->setName(app.getRelyingParty(entity.first)->getXMLString("entityID").second);
656 if (!req->getNameIDPolicy()) {
657 NameIDPolicy* namepol = NameIDPolicyBuilder::buildNameIDPolicy();
658 req->setNameIDPolicy(namepol);
659 namepol->AllowCreate(true);
661 if (NameIDFormat && *NameIDFormat) {
662 auto_ptr_XMLCh wideform(NameIDFormat);
663 req->getNameIDPolicy()->setFormat(wideform.get());
665 if (SPNameQualifier && *SPNameQualifier) {
666 auto_ptr_XMLCh widequal(SPNameQualifier);
667 req->getNameIDPolicy()->setSPNameQualifier(widequal.get());
669 if (authnContextClassRef || authnContextComparison) {
670 RequestedAuthnContext* reqContext = req->getRequestedAuthnContext();
672 reqContext = RequestedAuthnContextBuilder::buildRequestedAuthnContext();
673 req->setRequestedAuthnContext(reqContext);
675 if (authnContextClassRef) {
676 reqContext->getAuthnContextDeclRefs().clear();
677 auto_ptr_XMLCh wideclass(authnContextClassRef);
678 AuthnContextClassRef* cref = AuthnContextClassRefBuilder::buildAuthnContextClassRef();
679 cref->setReference(wideclass.get());
680 reqContext->getAuthnContextClassRefs().push_back(cref);
683 if (reqContext->getAuthnContextClassRefs().empty() && reqContext->getAuthnContextDeclRefs().empty()) {
684 req->setRequestedAuthnContext(nullptr);
686 else if (authnContextComparison) {
687 auto_ptr_XMLCh widecomp(authnContextComparison);
688 reqContext->setComparison(widecomp.get());
692 pair<bool,bool> requestDelegation = getBool("requestDelegation");
693 if (requestDelegation.first && requestDelegation.second && entity.first) {
694 // Request delegation by including the IdP as an Audience.
695 // Also specify the expected session lifetime as the bound on the assertion lifetime.
696 const PropertySet* sessionProps = app.getPropertySet("Sessions");
697 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
698 if (!lifetime.first || lifetime.second == 0)
699 lifetime.second = 28800;
700 if (!req->getConditions())
701 req->setConditions(ConditionsBuilder::buildConditions());
702 req->getConditions()->setNotOnOrAfter(time(nullptr) + lifetime.second + 300);
703 AudienceRestriction* audrest = AudienceRestrictionBuilder::buildAudienceRestriction();
704 req->getConditions()->getConditions().push_back(audrest);
705 Audience* aud = AudienceBuilder::buildAudience();
706 audrest->getAudiences().push_back(aud);
707 aud->setAudienceURI(entity.first->getEntityID());
710 if (ECP && entityID) {
711 auto_ptr_XMLCh wideid(entityID);
712 Scoping* scoping = req->getScoping();
714 scoping = ScopingBuilder::buildScoping();
715 req->setScoping(scoping);
717 IDPList* idplist = scoping->getIDPList();
719 idplist = IDPListBuilder::buildIDPList();
720 scoping->setIDPList(idplist);
722 VectorOf(IDPEntry) entries = idplist->getIDPEntrys();
723 if (find_if(entries, bind2nd(_sameIdP(), wideid.get())) == nullptr) {
724 IDPEntry* entry = IDPEntryBuilder::buildIDPEntry();
725 entry->setProviderID(wideid.get());
726 entries.push_back(entry);
730 auto_ptr_char dest(ep ? ep->getLocation() : nullptr);
733 // If the request object is available, we're responsible for the POST data.
734 preservePostData(app, *httpRequest, httpResponse, relayState.c_str());
737 long ret = sendMessage(
738 *encoder, req.get(), relayState.c_str(), dest.get(), role, app, httpResponse, role ? role->WantAuthnRequestsSigned() : false
740 req.release(); // freed by encoder
741 return make_pair(true,ret);
743 return make_pair(false,0L);