2 * Copyright 2001-2009 Internet2
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * SAML2SessionInitiator.cpp
20 * SAML 2.0 AuthnRequest support.
24 #include "Application.h"
25 #include "exceptions.h"
26 #include "ServiceProvider.h"
27 #include "SPRequest.h"
28 #include "handler/AbstractHandler.h"
29 #include "handler/RemotedHandler.h"
30 #include "handler/SessionInitiator.h"
31 #include "util/SPConstants.h"
34 # include "metadata/MetadataProviderCriteria.h"
35 # include <saml/SAMLConfig.h>
36 # include <saml/saml2/core/Protocols.h>
37 # include <saml/saml2/metadata/EndpointManager.h>
38 # include <saml/saml2/metadata/Metadata.h>
39 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
40 # include <saml/util/SAMLConstants.h>
41 using namespace opensaml::saml2;
42 using namespace opensaml::saml2p;
43 using namespace opensaml::saml2md;
45 # include "lite/SAMLConstants.h"
46 #include <xercesc/util/XMLUniDefs.hpp>
49 using namespace shibsp;
50 using namespace opensaml;
51 using namespace xmltooling;
56 #if defined (_MSC_VER)
57 #pragma warning( push )
58 #pragma warning( disable : 4250 )
61 class SHIBSP_DLLLOCAL SAML2SessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
64 SAML2SessionInitiator(const DOMElement* e, const char* appId);
65 virtual ~SAML2SessionInitiator() {
67 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
68 XMLString::release(&m_outgoing);
69 for_each(m_encoders.begin(), m_encoders.end(), cleanup_pair<const XMLCh*,MessageEncoder>());
70 delete m_requestTemplate;
76 void setParent(const PropertySet* parent);
77 void receive(DDF& in, ostream& out);
78 pair<bool,long> unwrap(SPRequest& request, DDF& out) const;
79 pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
82 pair<bool,long> doRequest(
83 const Application& application,
84 const HTTPRequest* httpRequest,
85 HTTPResponse& httpResponse,
87 const XMLCh* acsIndex,
89 const char* acsLocation,
90 const XMLCh* acsBinding,
93 const char* authnContextClassRef,
94 const char* authnContextComparison,
95 const char* NameIDFormat,
96 const char* SPNameQualifier,
101 auto_ptr_char m_paosNS,m_ecpNS;
102 auto_ptr_XMLCh m_paosBinding;
105 vector<const XMLCh*> m_bindings;
106 map<const XMLCh*,MessageEncoder*> m_encoders;
107 MessageEncoder* m_ecp;
108 AuthnRequest* m_requestTemplate;
114 #if defined (_MSC_VER)
115 #pragma warning( pop )
118 SessionInitiator* SHIBSP_DLLLOCAL SAML2SessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
120 return new SAML2SessionInitiator(p.first, p.second);
125 SAML2SessionInitiator::SAML2SessionInitiator(const DOMElement* e, const char* appId)
126 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.SAML2"), NULL, &m_remapper), m_appId(appId),
127 m_paosNS(samlconstants::PAOS_NS), m_ecpNS(samlconstants::SAML20ECP_NS), m_paosBinding(samlconstants::SAML20_BINDING_PAOS)
129 static const XMLCh ECP[] = UNICODE_LITERAL_3(E,C,P);
130 const XMLCh* flag = e ? e->getAttributeNS(NULL,ECP) : NULL;
132 m_ecp = (flag && (*flag == chLatin_t || *flag == chDigit_1));
136 m_requestTemplate=NULL;
138 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
139 // Check for a template AuthnRequest to build from.
140 DOMElement* child = XMLHelper::getFirstChildElement(e, samlconstants::SAML20P_NS, AuthnRequest::LOCAL_NAME);
142 m_requestTemplate = dynamic_cast<AuthnRequest*>(AuthnRequestBuilder::buildOneFromElement(child));
144 // If directed, build an ECP encoder.
145 if (flag && (*flag == chLatin_t || *flag == chDigit_1)) {
147 m_ecp = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
148 samlconstants::SAML20_BINDING_PAOS, pair<const DOMElement*,const XMLCh*>(e,NULL)
151 catch (exception& ex) {
152 m_log.error("error building PAOS/ECP MessageEncoder: %s", ex.what());
156 // Handle outgoing binding setup.
157 pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings");
158 if (outgoing.first) {
159 m_outgoing = XMLString::replicate(outgoing.second);
160 XMLString::trim(m_outgoing);
163 // No override, so we'll install a default binding precedence.
164 string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
165 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
166 m_outgoing = XMLString::transcode(prec.c_str());
170 XMLCh* start = m_outgoing;
171 while (start && *start) {
172 pos = XMLString::indexOf(start,chSpace);
174 *(start + pos)=chNull;
175 m_bindings.push_back(start);
177 auto_ptr_char b(start);
178 MessageEncoder * encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
179 b.get(),pair<const DOMElement*,const XMLCh*>(e,NULL)
181 if (encoder->isUserAgentPresent()) {
182 m_encoders[start] = encoder;
183 m_log.debug("supporting outgoing binding (%s)", b.get());
187 m_log.warn("skipping outgoing binding (%s), not a front-channel mechanism", b.get());
190 catch (exception& ex) {
191 m_log.error("error building MessageEncoder: %s", ex.what());
194 start = start + pos + 1;
201 // If Location isn't set, defer address registration until the setParent call.
202 pair<bool,const char*> loc = getString("Location");
204 string address = m_appId + loc.second + "::run::SAML2SI";
205 setAddress(address.c_str());
209 void SAML2SessionInitiator::setParent(const PropertySet* parent)
211 DOMPropertySet::setParent(parent);
212 pair<bool,const char*> loc = getString("Location");
214 string address = m_appId + loc.second + "::run::SAML2SI";
215 setAddress(address.c_str());
218 m_log.warn("no Location property in SAML2 SessionInitiator (or parent), can't register as remoted handler");
222 pair<bool,long> SAML2SessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
224 // First check for ECP support, since that doesn't require an IdP to be known.
226 if (m_ecp && request.getHeader("Accept").find("application/vnd.paos+xml") != string::npos) {
227 string PAOS = request.getHeader("PAOS");
228 if (PAOS.find(m_paosNS.get()) != string::npos && PAOS.find(m_ecpNS.get()) != string::npos)
232 // We have to know the IdP to function unless this is ECP.
233 if (!ECP && (entityID.empty()))
234 return make_pair(false,0L);
238 const Handler* ACS=NULL;
240 pair<bool,const char*> acClass, acComp, nidFormat, spQual;
241 bool isPassive=false,forceAuthn=false;
242 const Application& app=request.getApplication();
244 // ECP means the ACS will be by value no matter what.
245 pair<bool,bool> acsByIndex = ECP ? make_pair(true,false) : getBool("acsByIndex");
248 option=request.getParameter("acsIndex");
250 ACS = app.getAssertionConsumerServiceByIndex(atoi(option));
252 request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using acsIndex property");
253 else if (ECP && !XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_PAOS)) {
254 request.log(SPRequest::SPWarn, "acsIndex in request referenced a non-PAOS ACS, using default ACS location");
259 option = request.getParameter("target");
263 // Always need to recover target URL to compute handler below.
264 recoverRelayState(request.getApplication(), request, request, target, false);
266 pair<bool,bool> flag;
267 option = request.getParameter("isPassive");
269 isPassive = (*option=='1' || *option=='t');
272 flag = getBool("isPassive");
273 isPassive = (flag.first && flag.second);
276 option = request.getParameter("forceAuthn");
278 forceAuthn = (*option=='1' || *option=='t');
281 flag = getBool("forceAuthn");
282 forceAuthn = (flag.first && flag.second);
286 if (acClass.second = request.getParameter("authnContextClassRef"))
287 acClass.first = true;
289 acClass = getString("authnContextClassRef");
291 if (acComp.second = request.getParameter("authnContextComparison"))
294 acComp = getString("authnContextComparison");
296 if (nidFormat.second = request.getParameter("NameIDFormat"))
297 nidFormat.first = true;
299 nidFormat = getString("NameIDFormat");
301 if (spQual.second = request.getParameter("SPNameQualifier"))
304 spQual = getString("SPNameQualifier");
307 // We're running as a "virtual handler" from within the filter.
308 // The target resource is the current one and everything else is defaulted.
309 target=request.getRequestURL();
310 const PropertySet* settings = request.getRequestSettings().first;
312 pair<bool,bool> flag = settings->getBool("isPassive");
314 flag = getBool("isPassive");
315 isPassive = flag.first && flag.second;
317 flag = settings->getBool("forceAuthn");
319 flag = getBool("forceAuthn");
320 forceAuthn = flag.first && flag.second;
323 acClass = settings->getString("authnContextClassRef");
325 acClass = getString("authnContextClassRef");
326 acComp = settings->getString("authnContextComparison");
328 acComp = getString("authnContextComparison");
329 nidFormat = settings->getString("NameIDFormat");
330 if (!nidFormat.first)
331 nidFormat = getString("NameIDFormat");
332 spQual = settings->getString("SPNameQualifier");
334 spQual = getString("SPNameQualifier");
338 m_log.debug("attempting to initiate session using SAML 2.0 Enhanced Client Profile");
340 m_log.debug("attempting to initiate session using SAML 2.0 with provider (%s)", entityID.c_str());
344 const vector<const Handler*>& handlers = app.getAssertionConsumerServicesByBinding(m_paosBinding.get());
345 if (handlers.empty())
346 throw ConfigurationException("Unable to locate PAOS response endpoint.");
347 ACS = handlers.front();
350 pair<bool,unsigned int> index = getUnsignedInt("acsIndex");
352 ACS = app.getAssertionConsumerServiceByIndex(index.second);
354 request.log(SPRequest::SPWarn, "invalid acsIndex property, using default ACS location");
357 ACS = app.getDefaultAssertionConsumerService();
361 // Validate the ACS for use with this protocol.
363 pair<bool,const char*> ACSbinding = ACS ? ACS->getString("Binding") : pair<bool,const char*>(false,NULL);
364 if (ACSbinding.first) {
365 pair<bool,const char*> compatibleBindings = getString("compatibleBindings");
366 if (compatibleBindings.first && strstr(compatibleBindings.second, ACSbinding.second) == NULL) {
367 m_log.info("configured or requested ACS has non-SAML 2.0 binding");
368 return make_pair(false,0L);
370 else if (strcmp(ACSbinding.second, samlconstants::SAML20_BINDING_HTTP_POST) &&
371 strcmp(ACSbinding.second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT) &&
372 strcmp(ACSbinding.second, samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN)) {
373 m_log.info("configured or requested ACS has non-SAML 2.0 binding");
374 return make_pair(false,0L);
379 // To invoke the request builder, the key requirement is to figure out how
380 // to express the ACS, by index or value, and if by value, where.
381 // We have to compute the handlerURL no matter what, because we may need to
382 // flip the index to an SSL-version.
383 string ACSloc=request.getHandlerURL(target.c_str());
385 SPConfig& conf = SPConfig::getConfig();
386 if (conf.isEnabled(SPConfig::OutOfProcess)) {
387 if (acsByIndex.first && acsByIndex.second) {
390 // We may already have RelayState set if we looped back here,
391 // but just in case target is a resource, we reset it back.
393 option = request.getParameter("target");
398 // Determine index to use.
399 pair<bool,const XMLCh*> ix = pair<bool,const XMLCh*>(false,NULL);
401 if (!strncmp(ACSloc.c_str(), "https", 5)) {
402 ix = ACS->getXMLString("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
404 ix = ACS->getXMLString("index");
407 ix = ACS->getXMLString("index");
412 app, &request, request, entityID.c_str(),
414 ACS ? XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT) : false,
416 isPassive, forceAuthn,
417 acClass.first ? acClass.second : NULL,
418 acComp.first ? acComp.second : NULL,
419 nidFormat.first ? nidFormat.second : NULL,
420 spQual.first ? spQual.second : NULL,
425 // Since we're not passing by index, we need to fully compute the return URL and binding.
426 // Compute the ACS URL. We add the ACS location to the base handlerURL.
427 pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
428 if (loc.first) ACSloc+=loc.second;
431 // We may already have RelayState set if we looped back here,
432 // but just in case target is a resource, we reset it back.
434 option = request.getParameter("target");
440 app, &request, request, entityID.c_str(),
442 ACS ? XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT) : false,
443 ACSloc.c_str(), ACS ? ACS->getXMLString("Binding").second : NULL,
444 isPassive, forceAuthn,
445 acClass.first ? acClass.second : NULL,
446 acComp.first ? acComp.second : NULL,
447 nidFormat.first ? nidFormat.second : NULL,
448 spQual.first ? spQual.second : NULL,
454 DDF out,in = DDF(m_address.c_str()).structure();
455 DDFJanitor jin(in), jout(out);
456 in.addmember("application_id").string(app.getId());
457 if (!entityID.empty())
458 in.addmember("entity_id").string(entityID.c_str());
460 in.addmember("isPassive").integer(1);
462 in.addmember("forceAuthn").integer(1);
464 in.addmember("authnContextClassRef").string(acClass.second);
466 in.addmember("authnContextComparison").string(acComp.second);
468 in.addmember("NameIDFormat").string(nidFormat.second);
470 in.addmember("SPNameQualifier").string(spQual.second);
471 if (acsByIndex.first && acsByIndex.second) {
473 // Determine index to use.
474 pair<bool,const char*> ix = pair<bool,const char*>(false,NULL);
475 if (!strncmp(ACSloc.c_str(), "https", 5)) {
476 ix = ACS->getString("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
478 ix = ACS->getString("index");
481 ix = ACS->getString("index");
483 in.addmember("acsIndex").string(ix.second);
484 if (XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT))
485 in.addmember("artifact").integer(1);
489 // Since we're not passing by index, we need to fully compute the return URL and binding.
490 // Compute the ACS URL. We add the ACS location to the base handlerURL.
491 pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
492 if (loc.first) ACSloc+=loc.second;
493 in.addmember("acsLocation").string(ACSloc.c_str());
495 loc = ACS->getString("Binding");
496 in.addmember("acsBinding").string(loc.second);
497 if (XMLString::equals(loc.second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT))
498 in.addmember("artifact").integer(1);
503 // We may already have RelayState set if we looped back here,
504 // but just in case target is a resource, we reset it back.
506 option = request.getParameter("target");
511 in.addmember("RelayState").unsafe_string(target.c_str());
513 // Remote the processing.
514 out = request.getServiceProvider().getListenerService()->send(in);
515 return unwrap(request, out);
518 pair<bool,long> SAML2SessionInitiator::unwrap(SPRequest& request, DDF& out) const
520 // See if there's any response to send back.
521 if (!out["redirect"].isnull() || !out["response"].isnull()) {
522 // If so, we're responsible for handling the POST data, probably by dropping a cookie.
523 preservePostData(request.getApplication(), request, request, out["RelayState"].string());
525 return RemotedHandler::unwrap(request, out);
528 void SAML2SessionInitiator::receive(DDF& in, ostream& out)
531 const char* aid=in["application_id"].string();
532 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
534 // Something's horribly wrong.
535 m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
536 throw ConfigurationException("Unable to locate application for new session, deleted?");
540 DDFJanitor jout(ret);
542 // Wrap the outgoing object with a Response facade.
543 auto_ptr<HTTPResponse> http(getResponse(ret));
545 auto_ptr_XMLCh index(in["acsIndex"].string());
546 auto_ptr_XMLCh bind(in["acsBinding"].string());
548 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
549 string postData(in["PostData"].string() ? in["PostData"].string() : "");
551 // Since we're remoted, the result should either be a throw, which we pass on,
552 // a false/0 return, which we just return as an empty structure, or a response/redirect,
553 // which we capture in the facade and send back.
555 *app, NULL, *http.get(), in["entity_id"].string(),
557 (in["artifact"].integer() != 0),
558 in["acsLocation"].string(), bind.get(),
559 in["isPassive"].integer()==1, in["forceAuthn"].integer()==1,
560 in["authnContextClassRef"].string(), in["authnContextComparison"].string(),
561 in["NameIDFormat"].string(), in["SPNameQualifier"].string(),
566 ret.addmember("RelayState").unsafe_string(relayState.c_str());
572 class _sameIdP : public binary_function<const IDPEntry*, const XMLCh*, bool>
575 bool operator()(const IDPEntry* entry, const XMLCh* entityID) const {
576 return entry ? XMLString::equals(entry->getProviderID(), entityID) : false;
582 pair<bool,long> SAML2SessionInitiator::doRequest(
583 const Application& app,
584 const HTTPRequest* httpRequest,
585 HTTPResponse& httpResponse,
586 const char* entityID,
587 const XMLCh* acsIndex,
588 bool artifactInbound,
589 const char* acsLocation,
590 const XMLCh* acsBinding,
593 const char* authnContextClassRef,
594 const char* authnContextComparison,
595 const char* NameIDFormat,
596 const char* SPNameQualifier,
601 bool ECP = XMLString::equals(acsBinding, m_paosBinding.get());
603 pair<const EntityDescriptor*,const RoleDescriptor*> entity = pair<const EntityDescriptor*,const RoleDescriptor*>(NULL,NULL);
604 const IDPSSODescriptor* role = NULL;
605 const EndpointType* ep = NULL;
606 const MessageEncoder* encoder = NULL;
608 // We won't need this for ECP, but safety dictates we get the lock here.
609 MetadataProvider* m=app.getMetadataProvider();
615 m_log.error("MessageEncoder for PAOS binding not available");
616 return make_pair(false,0L);
620 // Use metadata to locate the IdP's SSO service.
621 MetadataProviderCriteria mc(app, entityID, &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
622 entity=m->getEntityDescriptor(mc);
624 m_log.warn("unable to locate metadata for provider (%s)", entityID);
625 throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
627 else if (!entity.second) {
628 m_log.log(getParent() ? Priority::INFO : Priority::WARN, "unable to locate SAML 2.0 identity provider role for provider (%s)", entityID);
630 return make_pair(false,0L);
631 throw MetadataException("Unable to locate SAML 2.0 identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
633 else if (artifactInbound && !SPConfig::getConfig().getArtifactResolver()->isSupported(dynamic_cast<const SSODescriptorType&>(*entity.second))) {
634 m_log.warn("artifact binding selected for response, but identity provider lacks support");
636 return make_pair(false,0L);
637 throw MetadataException("Identity provider ($entityID) lacks SAML 2.0 artifact support.", namedparams(1, "entityID", entityID));
640 // Loop over the supportable outgoing bindings.
641 role = dynamic_cast<const IDPSSODescriptor*>(entity.second);
642 vector<const XMLCh*>::const_iterator b;
643 for (b = m_bindings.begin(); b!=m_bindings.end(); ++b) {
644 if (ep=EndpointManager<SingleSignOnService>(role->getSingleSignOnServices()).getByBinding(*b)) {
645 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
646 if (enc!=m_encoders.end())
647 encoder = enc->second;
651 if (!ep || !encoder) {
652 m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
654 return make_pair(false,0L);
655 throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
659 preserveRelayState(app, httpResponse, relayState);
661 auto_ptr<AuthnRequest> req(m_requestTemplate ? m_requestTemplate->cloneAuthnRequest() : AuthnRequestBuilder::buildAuthnRequest());
662 if (m_requestTemplate) {
663 // Freshen TS and ID.
665 req->setIssueInstant(time(NULL));
669 req->setDestination(ep->getLocation());
670 if (acsIndex && *acsIndex)
671 req->setAssertionConsumerServiceIndex(acsIndex);
673 auto_ptr_XMLCh wideloc(acsLocation);
674 req->setAssertionConsumerServiceURL(wideloc.get());
676 if (acsBinding && *acsBinding)
677 req->setProtocolBinding(acsBinding);
679 req->IsPassive(isPassive);
681 req->ForceAuthn(forceAuthn);
682 if (!req->getIssuer()) {
683 Issuer* issuer = IssuerBuilder::buildIssuer();
684 req->setIssuer(issuer);
685 issuer->setName(app.getRelyingParty(entity.first)->getXMLString("entityID").second);
687 if (!req->getNameIDPolicy()) {
688 NameIDPolicy* namepol = NameIDPolicyBuilder::buildNameIDPolicy();
689 req->setNameIDPolicy(namepol);
690 namepol->AllowCreate(true);
692 if (NameIDFormat && *NameIDFormat) {
693 auto_ptr_XMLCh wideform(NameIDFormat);
694 req->getNameIDPolicy()->setFormat(wideform.get());
696 if (SPNameQualifier && *SPNameQualifier) {
697 auto_ptr_XMLCh widequal(SPNameQualifier);
698 req->getNameIDPolicy()->setSPNameQualifier(widequal.get());
700 if (authnContextClassRef || authnContextComparison) {
701 RequestedAuthnContext* reqContext = req->getRequestedAuthnContext();
703 reqContext = RequestedAuthnContextBuilder::buildRequestedAuthnContext();
704 req->setRequestedAuthnContext(reqContext);
706 if (authnContextClassRef) {
707 reqContext->getAuthnContextDeclRefs().clear();
708 auto_ptr_XMLCh wideclass(authnContextClassRef);
709 AuthnContextClassRef* cref = AuthnContextClassRefBuilder::buildAuthnContextClassRef();
710 cref->setReference(wideclass.get());
711 reqContext->getAuthnContextClassRefs().push_back(cref);
714 if (reqContext->getAuthnContextClassRefs().empty() && reqContext->getAuthnContextDeclRefs().empty()) {
715 req->setRequestedAuthnContext(NULL);
717 else if (authnContextComparison) {
718 auto_ptr_XMLCh widecomp(authnContextComparison);
719 reqContext->setComparison(widecomp.get());
723 pair<bool,bool> requestDelegation = getBool("requestDelegation");
724 if (requestDelegation.first && requestDelegation.second && entity.first) {
725 // Request delegation by including the IdP as an Audience.
726 // Also specify the expected session lifetime as the bound on the assertion lifetime.
727 const PropertySet* sessionProps = app.getPropertySet("Sessions");
728 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
729 if (!lifetime.first || lifetime.second == 0)
730 lifetime.second = 28800;
731 if (!req->getConditions())
732 req->setConditions(ConditionsBuilder::buildConditions());
733 req->getConditions()->setNotOnOrAfter(time(NULL) + lifetime.second + 300);
734 AudienceRestriction* audrest = AudienceRestrictionBuilder::buildAudienceRestriction();
735 req->getConditions()->getConditions().push_back(audrest);
736 Audience* aud = AudienceBuilder::buildAudience();
737 audrest->getAudiences().push_back(aud);
738 aud->setAudienceURI(entity.first->getEntityID());
741 if (ECP && entityID) {
742 auto_ptr_XMLCh wideid(entityID);
743 Scoping* scoping = req->getScoping();
745 scoping = ScopingBuilder::buildScoping();
746 req->setScoping(scoping);
748 IDPList* idplist = scoping->getIDPList();
750 idplist = IDPListBuilder::buildIDPList();
751 scoping->setIDPList(idplist);
753 VectorOf(IDPEntry) entries = idplist->getIDPEntrys();
754 if (find_if(entries, bind2nd(_sameIdP(), wideid.get())) == NULL) {
755 IDPEntry* entry = IDPEntryBuilder::buildIDPEntry();
756 entry->setProviderID(wideid.get());
757 entries.push_back(entry);
761 auto_ptr_char dest(ep ? ep->getLocation() : NULL);
764 // If the request object is available, we're responsible for the POST data.
765 preservePostData(app, *httpRequest, httpResponse, relayState.c_str());
768 long ret = sendMessage(
769 *encoder, req.get(), relayState.c_str(), dest.get(), role, app, httpResponse, role ? role->WantAuthnRequestsSigned() : false
771 req.release(); // freed by encoder
772 return make_pair(true,ret);
774 return make_pair(false,0L);