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 void generateMetadata(saml2md::SPSSODescriptor& role, const char* handlerURL) const {
89 doGenerateMetadata(role, handlerURL);
94 pair<bool,long> doRequest(
95 const Application& application,
96 const HTTPRequest* httpRequest,
97 HTTPResponse& httpResponse,
99 const XMLCh* acsIndex,
100 bool artifactInbound,
101 const char* acsLocation,
102 const XMLCh* acsBinding,
105 const char* authnContextClassRef,
106 const char* authnContextComparison,
107 const char* NameIDFormat,
108 const char* SPNameQualifier,
113 auto_ptr_char m_paosNS,m_ecpNS;
114 auto_ptr_XMLCh m_paosBinding;
116 vector<string> m_bindings;
117 map< string,boost::shared_ptr<MessageEncoder> > m_encoders;
118 scoped_ptr<MessageEncoder> m_ecp;
119 scoped_ptr<AuthnRequest> m_requestTemplate;
125 #if defined (_MSC_VER)
126 #pragma warning( pop )
129 class SHIBSP_DLLLOCAL SessionInitiatorNodeFilter : public DOMNodeFilter
132 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
137 acceptNode(const DOMNode* node) const {
138 return FILTER_REJECT;
142 static SHIBSP_DLLLOCAL SessionInitiatorNodeFilter g_SINFilter;
144 SessionInitiator* SHIBSP_DLLLOCAL SAML2SessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
146 return new SAML2SessionInitiator(p.first, p.second);
151 SAML2SessionInitiator::SAML2SessionInitiator(const DOMElement* e, const char* appId)
152 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT ".SessionInitiator.SAML2"), &g_SINFilter, &m_remapper), m_appId(appId),
153 m_paosNS(samlconstants::PAOS_NS), m_ecpNS(samlconstants::SAML20ECP_NS), m_paosBinding(samlconstants::SAML20_BINDING_PAOS)
159 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
160 // Check for a template AuthnRequest to build from.
161 DOMElement* child = XMLHelper::getFirstChildElement(e, samlconstants::SAML20P_NS, AuthnRequest::LOCAL_NAME);
163 m_requestTemplate.reset(dynamic_cast<AuthnRequest*>(AuthnRequestBuilder::buildOneFromElement(child)));
167 // If Location isn't set, defer initialization until the setParent call.
168 pair<bool,const char*> loc = getString("Location");
173 m_supportedOptions.insert("isPassive");
176 void SAML2SessionInitiator::setParent(const PropertySet* parent)
178 DOMPropertySet::setParent(parent);
179 pair<bool,const char*> loc = getString("Location");
183 void SAML2SessionInitiator::init(const char* location)
186 string address = m_appId + location + "::run::SAML2SI";
187 setAddress(address.c_str());
190 m_log.warn("no Location property in SAML2 SessionInitiator (or parent), can't register as remoted handler");
193 pair<bool,bool> flag = getBool("ECP");
195 m_ecp = flag.first && flag.second;
198 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
199 // If directed, build an ECP encoder.
200 if (flag.first && flag.second) {
203 SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
204 samlconstants::SAML20_BINDING_PAOS, pair<const DOMElement*,const XMLCh*>(getElement(), nullptr)
208 catch (std::exception& ex) {
209 m_log.error("error building PAOS/ECP MessageEncoder: %s", ex.what());
214 pair<bool,const char*> outgoing = getString("outgoingBindings");
215 if (outgoing.first) {
216 dupBindings = outgoing.second;
220 // No override, so we'll install a default binding precedence.
221 dupBindings = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
222 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
224 split(m_bindings, dupBindings, is_space(), algorithm::token_compress_on);
225 for (vector<string>::const_iterator b = m_bindings.begin(); b != m_bindings.end(); ++b) {
227 boost::shared_ptr<MessageEncoder> encoder(
228 SAMLConfig::getConfig().MessageEncoderManager.newPlugin(*b, pair<const DOMElement*,const XMLCh*>(getElement(),nullptr))
230 if (encoder->isUserAgentPresent() && XMLString::equals(getProtocolFamily(), encoder->getProtocolFamily())) {
231 m_encoders[*b] = encoder;
232 m_log.debug("supporting outgoing binding (%s)", b->c_str());
235 m_log.warn("skipping outgoing binding (%s), not a SAML 2.0 front-channel mechanism", b->c_str());
238 catch (std::exception& ex) {
239 m_log.error("error building MessageEncoder: %s", ex.what());
246 pair<bool,long> SAML2SessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
248 // First check for ECP support, since that doesn't require an IdP to be known.
250 if (m_ecp && request.getHeader("Accept").find("application/vnd.paos+xml") != string::npos) {
251 string PAOS = request.getHeader("PAOS");
252 if (PAOS.find(m_paosNS.get()) != string::npos && PAOS.find(m_ecpNS.get()) != string::npos)
256 // We have to know the IdP to function unless this is ECP.
257 if ((!ECP && entityID.empty()) || !checkCompatibility(request, isHandler))
258 return make_pair(false, 0L);
261 pair<bool,const char*> prop;
262 const Handler* ACS = nullptr;
263 pair<bool,const char*> acClass, acComp, nidFormat, spQual;
264 bool isPassive=false,forceAuthn=false;
265 const Application& app = request.getApplication();
267 // ECP means the ACS will be by value no matter what.
268 pair<bool,bool> acsByIndex = ECP ? make_pair(true,false) : getBool("acsByIndex");
271 prop.second = request.getParameter("acsIndex");
272 if (prop.second && *prop.second) {
273 ACS = app.getAssertionConsumerServiceByIndex(atoi(prop.second));
275 request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using acsIndex property");
276 else if (ECP && !XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_PAOS)) {
277 request.log(SPRequest::SPWarn, "acsIndex in request referenced a non-PAOS ACS, using default ACS location");
282 prop = getString("target", request);
284 target = prop.second;
286 // Always need to recover target URL to compute handler below.
287 recoverRelayState(app, request, request, target, false);
288 app.limitRedirect(request, target.c_str());
290 pair<bool,bool> flag = getBool("isPassive", request);
291 isPassive = (flag.first && flag.second);
294 flag = getBool("forceAuthn", request);
295 forceAuthn = (flag.first && flag.second);
298 // Populate via parameter, map, or property.
299 acClass = getString("authnContextClassRef", request);
300 acComp = getString("authnContextComparison", request);
301 nidFormat = getString("NameIDFormat", request);
302 spQual = getString("SPNameQualifier", request);
305 // Check for a hardwired target value in the map or handler.
306 prop = getString("target", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
308 target = prop.second;
310 target = request.getRequestURL();
312 pair<bool,bool> flag = getBool("isPassive", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
313 isPassive = flag.first && flag.second;
315 flag = getBool("forceAuthn", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
316 forceAuthn = flag.first && flag.second;
319 // Populate via map or property.
320 acClass = getString("authnContextClassRef", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
321 acComp = getString("authnContextComparison", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
322 nidFormat = getString("NameIDFormat", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
323 spQual = getString("SPNameQualifier", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
327 m_log.debug("attempting to initiate session using SAML 2.0 Enhanced Client Profile");
329 m_log.debug("attempting to initiate session using SAML 2.0 with provider (%s)", entityID.c_str());
333 ACS = app.getAssertionConsumerServiceByProtocol(getProtocolFamily(), samlconstants::SAML20_BINDING_PAOS);
335 throw ConfigurationException("Unable to locate PAOS response endpoint.");
338 // Try fixed index property.
339 pair<bool,unsigned int> index = getUnsignedInt("acsIndex", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
341 ACS = app.getAssertionConsumerServiceByIndex(index.second);
345 // If we picked by index, validate the ACS for use with this protocol.
346 if (!ECP && (!ACS || !XMLString::equals(getProtocolFamily(), ACS->getProtocolFamily()))) {
348 request.log(SPRequest::SPWarn, "invalid acsIndex property, or non-SAML 2.0 ACS, using default SAML 2.0 ACS");
349 ACS = app.getAssertionConsumerServiceByProtocol(getProtocolFamily());
351 throw ConfigurationException("Unable to locate a SAML 2.0 ACS endpoint to use for response.");
354 // To invoke the request builder, the key requirement is to figure out how
355 // to express the ACS, by index or value, and if by value, where.
356 // We have to compute the handlerURL no matter what, because we may need to
357 // flip the index to an SSL-version.
358 string ACSloc = request.getHandlerURL(target.c_str());
360 SPConfig& conf = SPConfig::getConfig();
361 if (conf.isEnabled(SPConfig::OutOfProcess)) {
362 if (acsByIndex.first && acsByIndex.second) {
365 // We may already have RelayState set if we looped back here,
366 // but we've turned it back into a resource by this point, so if there's
367 // a target on the URL, reset to that value.
368 prop.second = request.getParameter("target");
369 if (prop.second && *prop.second)
370 target = prop.second;
373 // Determine index to use.
374 pair<bool,const XMLCh*> ix = pair<bool,const XMLCh*>(false,nullptr);
375 if (!strncmp(ACSloc.c_str(), "https://", 8)) {
376 ix = ACS->getXMLString("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
378 ix = ACS->getXMLString("index");
381 ix = ACS->getXMLString("index");
385 app, &request, request, entityID.c_str(),
387 XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT),
389 isPassive, forceAuthn,
390 acClass.first ? acClass.second : nullptr,
391 acComp.first ? acComp.second : nullptr,
392 nidFormat.first ? nidFormat.second : nullptr,
393 spQual.first ? spQual.second : nullptr,
398 // Since we're not passing by index, we need to fully compute the return URL and binding.
399 // Compute the ACS URL. We add the ACS location to the base handlerURL.
400 prop = ACS->getString("Location");
402 ACSloc += prop.second;
405 // We may already have RelayState set if we looped back here,
406 // but we've turned it back into a resource by this point, so if there's
407 // a target on the URL, reset to that value.
408 prop.second = request.getParameter("target");
409 if (prop.second && *prop.second)
410 target = prop.second;
414 app, &request, request, entityID.c_str(),
416 XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT),
417 ACSloc.c_str(), ACS->getXMLString("Binding").second,
418 isPassive, forceAuthn,
419 acClass.first ? acClass.second : nullptr,
420 acComp.first ? acComp.second : nullptr,
421 nidFormat.first ? nidFormat.second : nullptr,
422 spQual.first ? spQual.second : nullptr,
428 DDF out,in = DDF(m_address.c_str()).structure();
429 DDFJanitor jin(in), jout(out);
430 in.addmember("application_id").string(app.getId());
431 if (!entityID.empty())
432 in.addmember("entity_id").string(entityID.c_str());
434 in.addmember("isPassive").integer(1);
436 in.addmember("forceAuthn").integer(1);
438 in.addmember("authnContextClassRef").string(acClass.second);
440 in.addmember("authnContextComparison").string(acComp.second);
442 in.addmember("NameIDFormat").string(nidFormat.second);
444 in.addmember("SPNameQualifier").string(spQual.second);
445 if (acsByIndex.first && acsByIndex.second) {
446 // Determine index to use.
447 pair<bool,const char*> ix = pair<bool,const char*>(false,nullptr);
448 if (!strncmp(ACSloc.c_str(), "https://", 8)) {
449 ix = ACS->getString("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
451 ix = ACS->getString("index");
454 ix = ACS->getString("index");
456 in.addmember("acsIndex").string(ix.second);
457 if (XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT))
458 in.addmember("artifact").integer(1);
461 // Since we're not passing by index, we need to fully compute the return URL and binding.
462 // Compute the ACS URL. We add the ACS location to the base handlerURL.
463 prop = ACS->getString("Location");
465 ACSloc += prop.second;
466 in.addmember("acsLocation").string(ACSloc.c_str());
467 prop = ACS->getString("Binding");
468 in.addmember("acsBinding").string(prop.second);
469 if (XMLString::equals(prop.second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT))
470 in.addmember("artifact").integer(1);
474 // We may already have RelayState set if we looped back here,
475 // but we've turned it back into a resource by this point, so if there's
476 // a target on the URL, reset to that value.
477 prop.second = request.getParameter("target");
478 if (prop.second && *prop.second)
479 target = prop.second;
482 in.addmember("RelayState").unsafe_string(target.c_str());
484 // Remote the processing.
485 out = request.getServiceProvider().getListenerService()->send(in);
486 return unwrap(request, out);
489 pair<bool,long> SAML2SessionInitiator::unwrap(SPRequest& request, DDF& out) const
491 // See if there's any response to send back.
492 if (!out["redirect"].isnull() || !out["response"].isnull()) {
493 // If so, we're responsible for handling the POST data, probably by dropping a cookie.
494 preservePostData(request.getApplication(), request, request, out["RelayState"].string());
496 return RemotedHandler::unwrap(request, out);
499 void SAML2SessionInitiator::receive(DDF& in, ostream& out)
502 const char* aid = in["application_id"].string();
503 const Application* app = aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
505 // Something's horribly wrong.
506 m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
507 throw ConfigurationException("Unable to locate application for new session, deleted?");
511 DDFJanitor jout(ret);
513 // Wrap the outgoing object with a Response facade.
514 scoped_ptr<HTTPResponse> http(getResponse(ret));
516 auto_ptr_XMLCh index(in["acsIndex"].string());
517 auto_ptr_XMLCh bind(in["acsBinding"].string());
519 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
520 string postData(in["PostData"].string() ? in["PostData"].string() : "");
522 // Since we're remoted, the result should either be a throw, which we pass on,
523 // a false/0 return, which we just return as an empty structure, or a response/redirect,
524 // which we capture in the facade and send back.
526 *app, nullptr, *http, in["entity_id"].string(),
528 (in["artifact"].integer() != 0),
529 in["acsLocation"].string(), bind.get(),
530 in["isPassive"].integer()==1, in["forceAuthn"].integer()==1,
531 in["authnContextClassRef"].string(), in["authnContextComparison"].string(),
532 in["NameIDFormat"].string(), in["SPNameQualifier"].string(),
537 ret.addmember("RelayState").unsafe_string(relayState.c_str());
541 pair<bool,long> SAML2SessionInitiator::doRequest(
542 const Application& app,
543 const HTTPRequest* httpRequest,
544 HTTPResponse& httpResponse,
545 const char* entityID,
546 const XMLCh* acsIndex,
547 bool artifactInbound,
548 const char* acsLocation,
549 const XMLCh* acsBinding,
552 const char* authnContextClassRef,
553 const char* authnContextComparison,
554 const char* NameIDFormat,
555 const char* SPNameQualifier,
560 bool ECP = XMLString::equals(acsBinding, m_paosBinding.get());
562 pair<const EntityDescriptor*,const RoleDescriptor*> entity = pair<const EntityDescriptor*,const RoleDescriptor*>(nullptr,nullptr);
563 const IDPSSODescriptor* role = nullptr;
564 const EndpointType* ep = nullptr;
565 const MessageEncoder* encoder = nullptr;
567 // We won't need this for ECP, but safety dictates we get the lock here.
568 MetadataProvider* m = app.getMetadataProvider();
572 encoder = m_ecp.get();
574 m_log.error("MessageEncoder for PAOS binding not available");
575 return make_pair(false, 0L);
579 // Use metadata to locate the IdP's SSO service.
580 MetadataProviderCriteria mc(app, entityID, &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
581 entity = m->getEntityDescriptor(mc);
583 m_log.warn("unable to locate metadata for provider (%s)", entityID);
584 throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
586 else if (!entity.second) {
587 m_log.log(getParent() ? Priority::INFO : Priority::WARN, "unable to locate SAML 2.0 identity provider role for provider (%s)", entityID);
589 return make_pair(false, 0L);
590 throw MetadataException("Unable to locate SAML 2.0 identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
592 else if (artifactInbound && !SPConfig::getConfig().getArtifactResolver()->isSupported(dynamic_cast<const SSODescriptorType&>(*entity.second))) {
593 m_log.warn("artifact binding selected for response, but identity provider lacks support");
595 return make_pair(false, 0L);
596 throw MetadataException("Identity provider ($entityID) lacks SAML 2.0 artifact support.", namedparams(1, "entityID", entityID));
599 // Loop over the supportable outgoing bindings.
600 role = dynamic_cast<const IDPSSODescriptor*>(entity.second);
601 for (vector<string>::const_iterator b = m_bindings.begin(); b != m_bindings.end(); ++b) {
602 auto_ptr_XMLCh wideb(b->c_str());
603 if (ep=EndpointManager<SingleSignOnService>(role->getSingleSignOnServices()).getByBinding(wideb.get())) {
604 map< string,boost::shared_ptr<MessageEncoder> >::const_iterator enc = m_encoders.find(*b);
605 if (enc != m_encoders.end())
606 encoder = enc->second.get();
610 if (!ep || !encoder) {
611 m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
613 return make_pair(false, 0L);
614 throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
618 preserveRelayState(app, httpResponse, relayState);
620 auto_ptr<AuthnRequest> req(m_requestTemplate ? m_requestTemplate->cloneAuthnRequest() : AuthnRequestBuilder::buildAuthnRequest());
621 if (m_requestTemplate) {
622 // Freshen TS and ID.
624 req->setIssueInstant(time(nullptr));
628 req->setDestination(ep->getLocation());
629 if (acsIndex && *acsIndex)
630 req->setAssertionConsumerServiceIndex(acsIndex);
632 auto_ptr_XMLCh wideloc(acsLocation);
633 req->setAssertionConsumerServiceURL(wideloc.get());
635 if (acsBinding && *acsBinding)
636 req->setProtocolBinding(acsBinding);
638 req->IsPassive(isPassive);
640 req->ForceAuthn(forceAuthn);
641 if (!req->getIssuer()) {
642 Issuer* issuer = IssuerBuilder::buildIssuer();
643 req->setIssuer(issuer);
644 issuer->setName(app.getRelyingParty(entity.first)->getXMLString("entityID").second);
646 if (!req->getNameIDPolicy()) {
647 NameIDPolicy* namepol = NameIDPolicyBuilder::buildNameIDPolicy();
648 req->setNameIDPolicy(namepol);
649 namepol->AllowCreate(true);
651 if (NameIDFormat && *NameIDFormat) {
652 auto_ptr_XMLCh wideform(NameIDFormat);
653 req->getNameIDPolicy()->setFormat(wideform.get());
655 if (SPNameQualifier && *SPNameQualifier) {
656 auto_ptr_XMLCh widequal(SPNameQualifier);
657 req->getNameIDPolicy()->setSPNameQualifier(widequal.get());
659 if (authnContextClassRef || authnContextComparison) {
660 RequestedAuthnContext* reqContext = req->getRequestedAuthnContext();
662 reqContext = RequestedAuthnContextBuilder::buildRequestedAuthnContext();
663 req->setRequestedAuthnContext(reqContext);
665 if (authnContextClassRef) {
666 reqContext->getAuthnContextDeclRefs().clear();
667 string dup(authnContextClassRef);
669 vector<string> contexts;
670 split(contexts, dup, is_space(), algorithm::token_compress_on);
671 for (vector<string>::const_iterator ac = contexts.begin(); ac != contexts.end(); ++ac) {
672 auto_ptr_XMLCh wideac(ac->c_str());
673 auto_ptr<AuthnContextClassRef> cref(AuthnContextClassRefBuilder::buildAuthnContextClassRef());
674 cref->setReference(wideac.get());
675 reqContext->getAuthnContextClassRefs().push_back(cref.get());
680 if (reqContext->getAuthnContextClassRefs().empty() && reqContext->getAuthnContextDeclRefs().empty()) {
681 req->setRequestedAuthnContext(nullptr);
683 else if (authnContextComparison) {
684 auto_ptr_XMLCh widecomp(authnContextComparison);
685 reqContext->setComparison(widecomp.get());
689 pair<bool,bool> requestDelegation = getBool("requestDelegation");
690 if (requestDelegation.first && requestDelegation.second) {
692 // Request delegation by including the IdP as an Audience.
693 // Also specify the expected session lifetime as the bound on the assertion lifetime.
694 const PropertySet* sessionProps = app.getPropertySet("Sessions");
695 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
696 if (!lifetime.first || lifetime.second == 0)
697 lifetime.second = 28800;
698 if (!req->getConditions())
699 req->setConditions(ConditionsBuilder::buildConditions());
700 req->getConditions()->setNotOnOrAfter(time(nullptr) + lifetime.second + 300);
701 AudienceRestriction* audrest = AudienceRestrictionBuilder::buildAudienceRestriction();
702 req->getConditions()->getConditions().push_back(audrest);
703 Audience* aud = AudienceBuilder::buildAudience();
704 audrest->getAudiences().push_back(aud);
705 aud->setAudienceURI(entity.first->getEntityID());
708 m_log.warn("requestDelegation set, but IdP unknown at request time");
712 if (ECP && entityID) {
713 auto_ptr_XMLCh wideid(entityID);
714 Scoping* scoping = req->getScoping();
716 scoping = ScopingBuilder::buildScoping();
717 req->setScoping(scoping);
719 IDPList* idplist = scoping->getIDPList();
721 idplist = IDPListBuilder::buildIDPList();
722 scoping->setIDPList(idplist);
724 VectorOf(IDPEntry) entries = idplist->getIDPEntrys();
725 static bool (*wideequals)(const XMLCh*,const XMLCh*) = &XMLString::equals;
726 if (find_if(entries, boost::bind(wideequals, boost::bind(&IDPEntry::getProviderID, _1), wideid.get())) == nullptr) {
727 IDPEntry* entry = IDPEntryBuilder::buildIDPEntry();
728 entry->setProviderID(wideid.get());
729 entries.push_back(entry);
733 XMLCh* genid = SAMLConfig::getConfig().generateIdentifier();
735 XMLString::release(&genid);
736 req->setIssueInstant(time(nullptr));
738 scoped_ptr<AuthnRequestEvent> ar_event(newAuthnRequestEvent(app, httpRequest));
740 auto_ptr_char b(ep ? ep->getBinding() : nullptr);
741 ar_event->m_binding = b.get() ? b.get() : samlconstants::SAML20_BINDING_SOAP;
742 auto_ptr_char prot(getProtocolFamily());
743 ar_event->m_protocol = prot.get();
744 ar_event->m_peer = entity.first;
745 ar_event->m_saml2Request = req.get();
746 app.getServiceProvider().getTransactionLog()->write(*ar_event);
749 auto_ptr_char dest(ep ? ep->getLocation() : nullptr);
752 // If the request object is available, we're responsible for the POST data.
753 preservePostData(app, *httpRequest, httpResponse, relayState.c_str());
756 long ret = sendMessage(
757 *encoder, req.get(), relayState.c_str(), dest.get(), role, app, httpResponse, role ? role->WantAuthnRequestsSigned() : false
759 req.release(); // freed by encoder
760 return make_pair(true, ret);
762 return make_pair(false, 0L);