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 <boost/bind.hpp>
39 # include <boost/algorithm/string.hpp>
40 # include <boost/iterator/indirect_iterator.hpp>
41 # include <saml/SAMLConfig.h>
42 # include <saml/saml2/core/Protocols.h>
43 # include <saml/saml2/metadata/EndpointManager.h>
44 # include <saml/saml2/metadata/Metadata.h>
45 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
46 # include <saml/util/SAMLConstants.h>
47 using namespace opensaml::saml2;
48 using namespace opensaml::saml2p;
49 using namespace opensaml::saml2md;
51 # include "lite/SAMLConstants.h"
52 # include <xercesc/util/XMLUniDefs.hpp>
55 #include <boost/scoped_ptr.hpp>
57 using namespace shibsp;
58 using namespace opensaml;
59 using namespace xmltooling;
60 using namespace boost;
65 #if defined (_MSC_VER)
66 #pragma warning( push )
67 #pragma warning( disable : 4250 )
70 class SHIBSP_DLLLOCAL SAML2SessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
73 SAML2SessionInitiator(const DOMElement* e, const char* appId);
74 virtual ~SAML2SessionInitiator() {}
76 void init(const char* location); // encapsulates actions that need to run either in the c'tor or setParent
78 void setParent(const PropertySet* parent);
79 void receive(DDF& in, ostream& out);
80 pair<bool,long> unwrap(SPRequest& request, DDF& out) const;
81 pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
83 const XMLCh* getProtocolFamily() const {
84 return samlconstants::SAML20P_NS;
88 pair<bool,long> doRequest(
89 const Application& application,
90 const HTTPRequest* httpRequest,
91 HTTPResponse& httpResponse,
93 const XMLCh* acsIndex,
95 const char* acsLocation,
96 const XMLCh* acsBinding,
99 const char* authnContextClassRef,
100 const char* authnContextComparison,
101 const char* NameIDFormat,
102 const char* SPNameQualifier,
107 auto_ptr_char m_paosNS,m_ecpNS;
108 auto_ptr_XMLCh m_paosBinding;
110 vector<string> m_bindings;
111 map< string,boost::shared_ptr<MessageEncoder> > m_encoders;
112 scoped_ptr<MessageEncoder> m_ecp;
113 scoped_ptr<AuthnRequest> m_requestTemplate;
119 #if defined (_MSC_VER)
120 #pragma warning( pop )
123 SessionInitiator* SHIBSP_DLLLOCAL SAML2SessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
125 return new SAML2SessionInitiator(p.first, p.second);
130 SAML2SessionInitiator::SAML2SessionInitiator(const DOMElement* e, const char* appId)
131 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.SAML2"), nullptr, &m_remapper), m_appId(appId),
132 m_paosNS(samlconstants::PAOS_NS), m_ecpNS(samlconstants::SAML20ECP_NS), m_paosBinding(samlconstants::SAML20_BINDING_PAOS)
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.reset(dynamic_cast<AuthnRequest*>(AuthnRequestBuilder::buildOneFromElement(child)));
146 // If Location isn't set, defer initialization until the setParent call.
147 pair<bool,const char*> loc = getString("Location");
152 m_supportedOptions.insert("isPassive");
155 void SAML2SessionInitiator::setParent(const PropertySet* parent)
157 DOMPropertySet::setParent(parent);
158 pair<bool,const char*> loc = getString("Location");
162 void SAML2SessionInitiator::init(const char* location)
165 string address = m_appId + location + "::run::SAML2SI";
166 setAddress(address.c_str());
169 m_log.warn("no Location property in SAML2 SessionInitiator (or parent), can't register as remoted handler");
172 pair<bool,bool> flag = getBool("ECP");
174 m_ecp = flag.first && flag.second;
177 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
178 // If directed, build an ECP encoder.
179 if (flag.first && flag.second) {
182 SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
183 samlconstants::SAML20_BINDING_PAOS, pair<const DOMElement*,const XMLCh*>(getElement(), nullptr)
187 catch (std::exception& ex) {
188 m_log.error("error building PAOS/ECP MessageEncoder: %s", ex.what());
193 pair<bool,const char*> outgoing = getString("outgoingBindings");
194 if (outgoing.first) {
195 dupBindings = outgoing.second;
198 // No override, so we'll install a default binding precedence.
199 dupBindings = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
200 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
202 split(m_bindings, dupBindings, is_space(), algorithm::token_compress_on);
203 for (vector<string>::const_iterator b = m_bindings.begin(); b != m_bindings.end(); ++b) {
205 boost::shared_ptr<MessageEncoder> encoder(
206 SAMLConfig::getConfig().MessageEncoderManager.newPlugin(*b, pair<const DOMElement*,const XMLCh*>(getElement(),nullptr))
208 if (encoder->isUserAgentPresent() && XMLString::equals(getProtocolFamily(), encoder->getProtocolFamily())) {
209 m_encoders[*b] = encoder;
210 m_log.debug("supporting outgoing binding (%s)", b->c_str());
213 m_log.warn("skipping outgoing binding (%s), not a SAML 2.0 front-channel mechanism", b->c_str());
216 catch (std::exception& ex) {
217 m_log.error("error building MessageEncoder: %s", ex.what());
224 pair<bool,long> SAML2SessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
226 // First check for ECP support, since that doesn't require an IdP to be known.
228 if (m_ecp && request.getHeader("Accept").find("application/vnd.paos+xml") != string::npos) {
229 string PAOS = request.getHeader("PAOS");
230 if (PAOS.find(m_paosNS.get()) != string::npos && PAOS.find(m_ecpNS.get()) != string::npos)
234 // We have to know the IdP to function unless this is ECP.
235 if ((!ECP && entityID.empty()) || !checkCompatibility(request, isHandler))
236 return make_pair(false, 0L);
239 pair<bool,const char*> prop;
240 const Handler* ACS = nullptr;
241 pair<bool,const char*> acClass, acComp, nidFormat, spQual;
242 bool isPassive=false,forceAuthn=false;
243 const Application& app = request.getApplication();
245 // ECP means the ACS will be by value no matter what.
246 pair<bool,bool> acsByIndex = ECP ? make_pair(true,false) : getBool("acsByIndex");
249 prop.second = request.getParameter("acsIndex");
250 if (prop.second && *prop.second) {
251 ACS = app.getAssertionConsumerServiceByIndex(atoi(prop.second));
253 request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using acsIndex property");
254 else if (ECP && !XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_PAOS)) {
255 request.log(SPRequest::SPWarn, "acsIndex in request referenced a non-PAOS ACS, using default ACS location");
260 prop = getString("target", request);
262 target = prop.second;
264 // Always need to recover target URL to compute handler below.
265 recoverRelayState(app, request, request, target, false);
266 limitRelayState(m_log, app, request, target.c_str());
268 pair<bool,bool> flag = getBool("isPassive", request);
269 isPassive = (flag.first && flag.second);
272 flag = getBool("forceAuthn", request);
273 forceAuthn = (flag.first && flag.second);
276 // Populate via parameter, map, or property.
277 acClass = getString("authnContextClassRef", request);
278 acComp = getString("authnContextComparison", request);
279 nidFormat = getString("NameIDFormat", request);
280 spQual = getString("SPNameQualifier", request);
283 // Check for a hardwired target value in the map or handler.
284 prop = getString("target", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
286 target = prop.second;
288 target = request.getRequestURL();
290 pair<bool,bool> flag = getBool("isPassive", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
291 isPassive = flag.first && flag.second;
293 flag = getBool("forceAuthn", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
294 forceAuthn = flag.first && flag.second;
297 // Populate via map or property.
298 acClass = getString("authnContextClassRef", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
299 acComp = getString("authnContextComparison", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
300 nidFormat = getString("NameIDFormat", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
301 spQual = getString("SPNameQualifier", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
305 m_log.debug("attempting to initiate session using SAML 2.0 Enhanced Client Profile");
307 m_log.debug("attempting to initiate session using SAML 2.0 with provider (%s)", entityID.c_str());
311 ACS = app.getAssertionConsumerServiceByProtocol(getProtocolFamily(), samlconstants::SAML20_BINDING_PAOS);
313 throw ConfigurationException("Unable to locate PAOS response endpoint.");
316 // Try fixed index property.
317 pair<bool,unsigned int> index = getUnsignedInt("acsIndex", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
319 ACS = app.getAssertionConsumerServiceByIndex(index.second);
323 // If we picked by index, validate the ACS for use with this protocol.
324 if (!ECP && (!ACS || !XMLString::equals(getProtocolFamily(), ACS->getProtocolFamily()))) {
326 request.log(SPRequest::SPWarn, "invalid acsIndex property, or non-SAML 2.0 ACS, using default SAML 2.0 ACS");
327 ACS = app.getAssertionConsumerServiceByProtocol(getProtocolFamily());
329 throw ConfigurationException("Unable to locate a SAML 2.0 ACS endpoint to use for response.");
332 // To invoke the request builder, the key requirement is to figure out how
333 // to express the ACS, by index or value, and if by value, where.
334 // We have to compute the handlerURL no matter what, because we may need to
335 // flip the index to an SSL-version.
336 string ACSloc = request.getHandlerURL(target.c_str());
338 SPConfig& conf = SPConfig::getConfig();
339 if (conf.isEnabled(SPConfig::OutOfProcess)) {
340 if (acsByIndex.first && acsByIndex.second) {
343 // We may already have RelayState set if we looped back here,
344 // but we've turned it back into a resource by this point, so if there's
345 // a target on the URL, reset to that value.
346 prop.second = request.getParameter("target");
347 if (prop.second && *prop.second)
348 target = prop.second;
351 // Determine index to use.
352 pair<bool,const XMLCh*> ix = pair<bool,const XMLCh*>(false,nullptr);
353 if (!strncmp(ACSloc.c_str(), "https://", 8)) {
354 ix = ACS->getXMLString("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
356 ix = ACS->getXMLString("index");
359 ix = ACS->getXMLString("index");
363 app, &request, request, entityID.c_str(),
365 XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT),
367 isPassive, forceAuthn,
368 acClass.first ? acClass.second : nullptr,
369 acComp.first ? acComp.second : nullptr,
370 nidFormat.first ? nidFormat.second : nullptr,
371 spQual.first ? spQual.second : nullptr,
376 // Since we're not passing by index, we need to fully compute the return URL and binding.
377 // Compute the ACS URL. We add the ACS location to the base handlerURL.
378 prop = ACS->getString("Location");
380 ACSloc += prop.second;
383 // We may already have RelayState set if we looped back here,
384 // but we've turned it back into a resource by this point, so if there's
385 // a target on the URL, reset to that value.
386 prop.second = request.getParameter("target");
387 if (prop.second && *prop.second)
388 target = prop.second;
392 app, &request, request, entityID.c_str(),
394 XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT),
395 ACSloc.c_str(), ACS->getXMLString("Binding").second,
396 isPassive, forceAuthn,
397 acClass.first ? acClass.second : nullptr,
398 acComp.first ? acComp.second : nullptr,
399 nidFormat.first ? nidFormat.second : nullptr,
400 spQual.first ? spQual.second : nullptr,
406 DDF out,in = DDF(m_address.c_str()).structure();
407 DDFJanitor jin(in), jout(out);
408 in.addmember("application_id").string(app.getId());
409 if (!entityID.empty())
410 in.addmember("entity_id").string(entityID.c_str());
412 in.addmember("isPassive").integer(1);
414 in.addmember("forceAuthn").integer(1);
416 in.addmember("authnContextClassRef").string(acClass.second);
418 in.addmember("authnContextComparison").string(acComp.second);
420 in.addmember("NameIDFormat").string(nidFormat.second);
422 in.addmember("SPNameQualifier").string(spQual.second);
423 if (acsByIndex.first && acsByIndex.second) {
424 // Determine index to use.
425 pair<bool,const char*> ix = pair<bool,const char*>(false,nullptr);
426 if (!strncmp(ACSloc.c_str(), "https://", 8)) {
427 ix = ACS->getString("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
429 ix = ACS->getString("index");
432 ix = ACS->getString("index");
434 in.addmember("acsIndex").string(ix.second);
435 if (XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT))
436 in.addmember("artifact").integer(1);
439 // Since we're not passing by index, we need to fully compute the return URL and binding.
440 // Compute the ACS URL. We add the ACS location to the base handlerURL.
441 prop = ACS->getString("Location");
443 ACSloc += prop.second;
444 in.addmember("acsLocation").string(ACSloc.c_str());
445 prop = ACS->getString("Binding");
446 in.addmember("acsBinding").string(prop.second);
447 if (XMLString::equals(prop.second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT))
448 in.addmember("artifact").integer(1);
452 // We may already have RelayState set if we looped back here,
453 // but we've turned it back into a resource by this point, so if there's
454 // a target on the URL, reset to that value.
455 prop.second = request.getParameter("target");
456 if (prop.second && *prop.second)
457 target = prop.second;
460 in.addmember("RelayState").unsafe_string(target.c_str());
462 // Remote the processing.
463 out = request.getServiceProvider().getListenerService()->send(in);
464 return unwrap(request, out);
467 pair<bool,long> SAML2SessionInitiator::unwrap(SPRequest& request, DDF& out) const
469 // See if there's any response to send back.
470 if (!out["redirect"].isnull() || !out["response"].isnull()) {
471 // If so, we're responsible for handling the POST data, probably by dropping a cookie.
472 preservePostData(request.getApplication(), request, request, out["RelayState"].string());
474 return RemotedHandler::unwrap(request, out);
477 void SAML2SessionInitiator::receive(DDF& in, ostream& out)
480 const char* aid = in["application_id"].string();
481 const Application* app = aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
483 // Something's horribly wrong.
484 m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
485 throw ConfigurationException("Unable to locate application for new session, deleted?");
489 DDFJanitor jout(ret);
491 // Wrap the outgoing object with a Response facade.
492 scoped_ptr<HTTPResponse> http(getResponse(ret));
494 auto_ptr_XMLCh index(in["acsIndex"].string());
495 auto_ptr_XMLCh bind(in["acsBinding"].string());
497 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
498 string postData(in["PostData"].string() ? in["PostData"].string() : "");
500 // Since we're remoted, the result should either be a throw, which we pass on,
501 // a false/0 return, which we just return as an empty structure, or a response/redirect,
502 // which we capture in the facade and send back.
504 *app, nullptr, *http, in["entity_id"].string(),
506 (in["artifact"].integer() != 0),
507 in["acsLocation"].string(), bind.get(),
508 in["isPassive"].integer()==1, in["forceAuthn"].integer()==1,
509 in["authnContextClassRef"].string(), in["authnContextComparison"].string(),
510 in["NameIDFormat"].string(), in["SPNameQualifier"].string(),
515 ret.addmember("RelayState").unsafe_string(relayState.c_str());
519 pair<bool,long> SAML2SessionInitiator::doRequest(
520 const Application& app,
521 const HTTPRequest* httpRequest,
522 HTTPResponse& httpResponse,
523 const char* entityID,
524 const XMLCh* acsIndex,
525 bool artifactInbound,
526 const char* acsLocation,
527 const XMLCh* acsBinding,
530 const char* authnContextClassRef,
531 const char* authnContextComparison,
532 const char* NameIDFormat,
533 const char* SPNameQualifier,
538 bool ECP = XMLString::equals(acsBinding, m_paosBinding.get());
540 pair<const EntityDescriptor*,const RoleDescriptor*> entity = pair<const EntityDescriptor*,const RoleDescriptor*>(nullptr,nullptr);
541 const IDPSSODescriptor* role = nullptr;
542 const EndpointType* ep = nullptr;
543 const MessageEncoder* encoder = nullptr;
545 // We won't need this for ECP, but safety dictates we get the lock here.
546 MetadataProvider* m = app.getMetadataProvider();
550 encoder = m_ecp.get();
552 m_log.error("MessageEncoder for PAOS binding not available");
553 return make_pair(false, 0L);
557 // Use metadata to locate the IdP's SSO service.
558 MetadataProviderCriteria mc(app, entityID, &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
559 entity = m->getEntityDescriptor(mc);
561 m_log.warn("unable to locate metadata for provider (%s)", entityID);
562 throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
564 else if (!entity.second) {
565 m_log.log(getParent() ? Priority::INFO : Priority::WARN, "unable to locate SAML 2.0 identity provider role for provider (%s)", entityID);
567 return make_pair(false, 0L);
568 throw MetadataException("Unable to locate SAML 2.0 identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
570 else if (artifactInbound && !SPConfig::getConfig().getArtifactResolver()->isSupported(dynamic_cast<const SSODescriptorType&>(*entity.second))) {
571 m_log.warn("artifact binding selected for response, but identity provider lacks support");
573 return make_pair(false, 0L);
574 throw MetadataException("Identity provider ($entityID) lacks SAML 2.0 artifact support.", namedparams(1, "entityID", entityID));
577 // Loop over the supportable outgoing bindings.
578 role = dynamic_cast<const IDPSSODescriptor*>(entity.second);
579 for (vector<string>::const_iterator b = m_bindings.begin(); b != m_bindings.end(); ++b) {
580 auto_ptr_XMLCh wideb(b->c_str());
581 if (ep=EndpointManager<SingleSignOnService>(role->getSingleSignOnServices()).getByBinding(wideb.get())) {
582 map< string,boost::shared_ptr<MessageEncoder> >::const_iterator enc = m_encoders.find(*b);
583 if (enc != m_encoders.end())
584 encoder = enc->second.get();
588 if (!ep || !encoder) {
589 m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
591 return make_pair(false, 0L);
592 throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
596 preserveRelayState(app, httpResponse, relayState);
598 auto_ptr<AuthnRequest> req(m_requestTemplate ? m_requestTemplate->cloneAuthnRequest() : AuthnRequestBuilder::buildAuthnRequest());
599 if (m_requestTemplate) {
600 // Freshen TS and ID.
602 req->setIssueInstant(time(nullptr));
606 req->setDestination(ep->getLocation());
607 if (acsIndex && *acsIndex)
608 req->setAssertionConsumerServiceIndex(acsIndex);
610 auto_ptr_XMLCh wideloc(acsLocation);
611 req->setAssertionConsumerServiceURL(wideloc.get());
613 if (acsBinding && *acsBinding)
614 req->setProtocolBinding(acsBinding);
616 req->IsPassive(isPassive);
618 req->ForceAuthn(forceAuthn);
619 if (!req->getIssuer()) {
620 Issuer* issuer = IssuerBuilder::buildIssuer();
621 req->setIssuer(issuer);
622 issuer->setName(app.getRelyingParty(entity.first)->getXMLString("entityID").second);
624 if (!req->getNameIDPolicy()) {
625 NameIDPolicy* namepol = NameIDPolicyBuilder::buildNameIDPolicy();
626 req->setNameIDPolicy(namepol);
627 namepol->AllowCreate(true);
629 if (NameIDFormat && *NameIDFormat) {
630 auto_ptr_XMLCh wideform(NameIDFormat);
631 req->getNameIDPolicy()->setFormat(wideform.get());
633 if (SPNameQualifier && *SPNameQualifier) {
634 auto_ptr_XMLCh widequal(SPNameQualifier);
635 req->getNameIDPolicy()->setSPNameQualifier(widequal.get());
637 if (authnContextClassRef || authnContextComparison) {
638 RequestedAuthnContext* reqContext = req->getRequestedAuthnContext();
640 reqContext = RequestedAuthnContextBuilder::buildRequestedAuthnContext();
641 req->setRequestedAuthnContext(reqContext);
643 if (authnContextClassRef) {
644 reqContext->getAuthnContextDeclRefs().clear();
645 string dup(authnContextClassRef);
646 vector<string> contexts;
647 split(contexts, dup, is_space(), algorithm::token_compress_on);
648 for (vector<string>::const_iterator ac = contexts.begin(); ac != contexts.end(); ++ac) {
649 auto_ptr_XMLCh wideac(ac->c_str());
650 auto_ptr<AuthnContextClassRef> cref(AuthnContextClassRefBuilder::buildAuthnContextClassRef());
651 cref->setReference(wideac.get());
652 reqContext->getAuthnContextClassRefs().push_back(cref.get());
657 if (reqContext->getAuthnContextClassRefs().empty() && reqContext->getAuthnContextDeclRefs().empty()) {
658 req->setRequestedAuthnContext(nullptr);
660 else if (authnContextComparison) {
661 auto_ptr_XMLCh widecomp(authnContextComparison);
662 reqContext->setComparison(widecomp.get());
666 pair<bool,bool> requestDelegation = getBool("requestDelegation");
667 if (requestDelegation.first && requestDelegation.second && entity.first) {
668 // Request delegation by including the IdP as an Audience.
669 // Also specify the expected session lifetime as the bound on the assertion lifetime.
670 const PropertySet* sessionProps = app.getPropertySet("Sessions");
671 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
672 if (!lifetime.first || lifetime.second == 0)
673 lifetime.second = 28800;
674 if (!req->getConditions())
675 req->setConditions(ConditionsBuilder::buildConditions());
676 req->getConditions()->setNotOnOrAfter(time(nullptr) + lifetime.second + 300);
677 AudienceRestriction* audrest = AudienceRestrictionBuilder::buildAudienceRestriction();
678 req->getConditions()->getConditions().push_back(audrest);
679 Audience* aud = AudienceBuilder::buildAudience();
680 audrest->getAudiences().push_back(aud);
681 aud->setAudienceURI(entity.first->getEntityID());
684 if (ECP && entityID) {
685 auto_ptr_XMLCh wideid(entityID);
686 Scoping* scoping = req->getScoping();
688 scoping = ScopingBuilder::buildScoping();
689 req->setScoping(scoping);
691 IDPList* idplist = scoping->getIDPList();
693 idplist = IDPListBuilder::buildIDPList();
694 scoping->setIDPList(idplist);
696 VectorOf(IDPEntry) entries = idplist->getIDPEntrys();
697 static bool (*wideequals)(const XMLCh*,const XMLCh*) = &XMLString::equals;
698 if (find_if(entries, boost::bind(wideequals, boost::bind(&IDPEntry::getProviderID, _1), wideid.get())) == nullptr) {
699 IDPEntry* entry = IDPEntryBuilder::buildIDPEntry();
700 entry->setProviderID(wideid.get());
701 entries.push_back(entry);
705 req->setID(SAMLConfig::getConfig().generateIdentifier());
706 req->setIssueInstant(time(nullptr));
708 scoped_ptr<AuthnRequestEvent> ar_event(newAuthnRequestEvent(app, httpRequest));
710 auto_ptr_char b(ep ? ep->getBinding() : nullptr);
711 ar_event->m_binding = b.get() ? b.get() : samlconstants::SAML20_BINDING_SOAP;
712 auto_ptr_char prot(getProtocolFamily());
713 ar_event->m_protocol = prot.get();
714 ar_event->m_peer = entity.first;
715 ar_event->m_saml2Request = req.get();
716 app.getServiceProvider().getTransactionLog()->write(*ar_event);
719 auto_ptr_char dest(ep ? ep->getLocation() : nullptr);
722 // If the request object is available, we're responsible for the POST data.
723 preservePostData(app, *httpRequest, httpResponse, relayState.c_str());
726 long ret = sendMessage(
727 *encoder, req.get(), relayState.c_str(), dest.get(), role, app, httpResponse, role ? role->WantAuthnRequestsSigned() : false
729 req.release(); // freed by encoder
730 return make_pair(true, ret);
732 return make_pair(false, 0L);