2 * Copyright 2001-2010 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 "handler/AbstractHandler.h"
28 #include "handler/RemotedHandler.h"
29 #include "handler/SessionInitiator.h"
30 #include "util/SPConstants.h"
33 # include "metadata/MetadataProviderCriteria.h"
34 # include <saml/SAMLConfig.h>
35 # include <saml/saml2/core/Protocols.h>
36 # include <saml/saml2/metadata/EndpointManager.h>
37 # include <saml/saml2/metadata/Metadata.h>
38 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
39 # include <saml/util/SAMLConstants.h>
40 using namespace opensaml::saml2;
41 using namespace opensaml::saml2p;
42 using namespace opensaml::saml2md;
44 # include "lite/SAMLConstants.h"
45 #include <xercesc/util/XMLUniDefs.hpp>
48 using namespace shibsp;
49 using namespace opensaml;
50 using namespace xmltooling;
55 #if defined (_MSC_VER)
56 #pragma warning( push )
57 #pragma warning( disable : 4250 )
60 class SHIBSP_DLLLOCAL SAML2SessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
63 SAML2SessionInitiator(const DOMElement* e, const char* appId);
64 virtual ~SAML2SessionInitiator() {
66 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
67 XMLString::release(&m_outgoing);
68 for_each(m_encoders.begin(), m_encoders.end(), cleanup_pair<const XMLCh*,MessageEncoder>());
69 delete m_requestTemplate;
75 void setParent(const PropertySet* parent);
76 void receive(DDF& in, ostream& out);
77 pair<bool,long> unwrap(SPRequest& request, DDF& out) const;
78 pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
81 pair<bool,long> doRequest(
82 const Application& application,
83 const HTTPRequest* httpRequest,
84 HTTPResponse& httpResponse,
86 const XMLCh* acsIndex,
88 const char* acsLocation,
89 const XMLCh* acsBinding,
92 const char* authnContextClassRef,
93 const char* authnContextComparison,
94 const char* NameIDFormat,
95 const char* SPNameQualifier,
100 auto_ptr_char m_paosNS,m_ecpNS;
101 auto_ptr_XMLCh m_paosBinding;
104 vector<const XMLCh*> m_bindings;
105 map<const XMLCh*,MessageEncoder*> m_encoders;
106 MessageEncoder* m_ecp;
107 AuthnRequest* m_requestTemplate;
113 #if defined (_MSC_VER)
114 #pragma warning( pop )
117 SessionInitiator* SHIBSP_DLLLOCAL SAML2SessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
119 return new SAML2SessionInitiator(p.first, p.second);
124 SAML2SessionInitiator::SAML2SessionInitiator(const DOMElement* e, const char* appId)
125 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.SAML2"), NULL, &m_remapper), m_appId(appId),
126 m_paosNS(samlconstants::PAOS_NS), m_ecpNS(samlconstants::SAML20ECP_NS), m_paosBinding(samlconstants::SAML20_BINDING_PAOS)
128 static const XMLCh ECP[] = UNICODE_LITERAL_3(E,C,P);
129 const XMLCh* flag = e ? e->getAttributeNS(NULL,ECP) : NULL;
131 m_ecp = (flag && (*flag == chLatin_t || *flag == chDigit_1));
135 m_requestTemplate=NULL;
137 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
138 // Check for a template AuthnRequest to build from.
139 DOMElement* child = XMLHelper::getFirstChildElement(e, samlconstants::SAML20P_NS, AuthnRequest::LOCAL_NAME);
141 m_requestTemplate = dynamic_cast<AuthnRequest*>(AuthnRequestBuilder::buildOneFromElement(child));
143 // If directed, build an ECP encoder.
144 if (flag && (*flag == chLatin_t || *flag == chDigit_1)) {
146 m_ecp = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
147 samlconstants::SAML20_BINDING_PAOS, pair<const DOMElement*,const XMLCh*>(e,NULL)
150 catch (exception& ex) {
151 m_log.error("error building PAOS/ECP MessageEncoder: %s", ex.what());
155 // Handle outgoing binding setup.
156 pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings");
157 if (outgoing.first) {
158 m_outgoing = XMLString::replicate(outgoing.second);
159 XMLString::trim(m_outgoing);
162 // No override, so we'll install a default binding precedence.
163 string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
164 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
165 m_outgoing = XMLString::transcode(prec.c_str());
169 XMLCh* start = m_outgoing;
170 while (start && *start) {
171 pos = XMLString::indexOf(start,chSpace);
173 *(start + pos)=chNull;
174 m_bindings.push_back(start);
176 auto_ptr_char b(start);
177 MessageEncoder * encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
178 b.get(),pair<const DOMElement*,const XMLCh*>(e,NULL)
180 if (encoder->isUserAgentPresent()) {
181 m_encoders[start] = encoder;
182 m_log.debug("supporting outgoing binding (%s)", b.get());
186 m_log.warn("skipping outgoing binding (%s), not a front-channel mechanism", b.get());
189 catch (exception& ex) {
190 m_log.error("error building MessageEncoder: %s", ex.what());
193 start = start + pos + 1;
200 // If Location isn't set, defer address registration until the setParent call.
201 pair<bool,const char*> loc = getString("Location");
203 string address = m_appId + loc.second + "::run::SAML2SI";
204 setAddress(address.c_str());
207 m_supportedOptions.insert("isPassive");
210 void SAML2SessionInitiator::setParent(const PropertySet* parent)
212 DOMPropertySet::setParent(parent);
213 pair<bool,const char*> loc = getString("Location");
215 string address = m_appId + loc.second + "::run::SAML2SI";
216 setAddress(address.c_str());
219 m_log.warn("no Location property in SAML2 SessionInitiator (or parent), can't register as remoted handler");
223 pair<bool,long> SAML2SessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
225 // First check for ECP support, since that doesn't require an IdP to be known.
227 if (m_ecp && request.getHeader("Accept").find("application/vnd.paos+xml") != string::npos) {
228 string PAOS = request.getHeader("PAOS");
229 if (PAOS.find(m_paosNS.get()) != string::npos && PAOS.find(m_ecpNS.get()) != string::npos)
233 // We have to know the IdP to function unless this is ECP.
234 if ((!ECP && entityID.empty()) || !checkCompatibility(request, isHandler))
235 return make_pair(false,0L);
238 pair<bool,const char*> prop;
239 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 prop.second = request.getParameter("acsIndex");
249 if (prop.second && *prop.second) {
250 ACS = app.getAssertionConsumerServiceByIndex(atoi(prop.second));
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 prop = getString("target", request);
261 target = prop.second;
263 // Always need to recover target URL to compute handler below.
264 recoverRelayState(app, request, request, target, false);
266 pair<bool,bool> flag = getBool("isPassive", request);
267 isPassive = (flag.first && flag.second);
270 flag = getBool("forceAuthn", request);
271 forceAuthn = (flag.first && flag.second);
274 // Populate via parameter, map, or property.
275 acClass = getString("authnContextClassRef", request);
276 acComp = getString("authnContextComparison", request);
277 nidFormat = getString("NameIDFormat", request);
278 spQual = getString("SPNameQualifier", request);
281 // Check for a hardwired target value in the map or handler.
282 prop = getString("target", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
284 target = prop.second;
286 target = request.getRequestURL();
288 pair<bool,bool> flag = getBool("isPassive", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
289 isPassive = flag.first && flag.second;
291 flag = getBool("forceAuthn", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
292 forceAuthn = flag.first && flag.second;
295 // Populate via map or property.
296 acClass = getString("authnContextClassRef", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
297 acComp = getString("authnContextComparison", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
298 nidFormat = getString("NameIDFormat", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
299 spQual = getString("SPNameQualifier", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
303 m_log.debug("attempting to initiate session using SAML 2.0 Enhanced Client Profile");
305 m_log.debug("attempting to initiate session using SAML 2.0 with provider (%s)", entityID.c_str());
309 const vector<const Handler*>& handlers = app.getAssertionConsumerServicesByBinding(m_paosBinding.get());
310 if (handlers.empty())
311 throw ConfigurationException("Unable to locate PAOS response endpoint.");
312 ACS = handlers.front();
315 pair<bool,unsigned int> index = getUnsignedInt("acsIndex", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
317 ACS = app.getAssertionConsumerServiceByIndex(index.second);
319 request.log(SPRequest::SPWarn, "invalid acsIndex property, using default ACS location");
322 ACS = app.getDefaultAssertionConsumerService();
326 // Validate the ACS for use with this protocol.
328 pair<bool,const char*> ACSbinding = ACS ? ACS->getString("Binding") : pair<bool,const char*>(false,NULL);
329 if (ACSbinding.first) {
330 pair<bool,const char*> compatibleBindings = getString("compatibleBindings");
331 if (compatibleBindings.first && strstr(compatibleBindings.second, ACSbinding.second) == NULL) {
332 m_log.error("configured or requested ACS has non-SAML 2.0 binding");
333 throw ConfigurationException("Configured or requested ACS has non-SAML 2.0 binding ($1).", params(1, ACSbinding.second));
335 else if (strcmp(ACSbinding.second, samlconstants::SAML20_BINDING_HTTP_POST) &&
336 strcmp(ACSbinding.second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT) &&
337 strcmp(ACSbinding.second, samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN)) {
338 m_log.error("configured or requested ACS has non-SAML 2.0 binding");
339 throw ConfigurationException("Configured or requested ACS has non-SAML 2.0 binding ($1).", params(1, ACSbinding.second));
344 // To invoke the request builder, the key requirement is to figure out how
345 // to express the ACS, by index or value, and if by value, where.
346 // We have to compute the handlerURL no matter what, because we may need to
347 // flip the index to an SSL-version.
348 string ACSloc = request.getHandlerURL(target.c_str());
350 SPConfig& conf = SPConfig::getConfig();
351 if (conf.isEnabled(SPConfig::OutOfProcess)) {
352 if (acsByIndex.first && acsByIndex.second) {
355 // We may already have RelayState set if we looped back here,
356 // but we've turned it back into a resource by this point, so if there's
357 // a target on the URL, reset to that value.
358 prop.second = request.getParameter("target");
359 if (prop.second && *prop.second)
360 target = prop.second;
363 // Determine index to use.
364 pair<bool,const XMLCh*> ix = pair<bool,const XMLCh*>(false,NULL);
366 if (!strncmp(ACSloc.c_str(), "https", 5)) {
367 ix = ACS->getXMLString("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
369 ix = ACS->getXMLString("index");
372 ix = ACS->getXMLString("index");
377 app, &request, request, entityID.c_str(),
379 ACS ? XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT) : false,
381 isPassive, forceAuthn,
382 acClass.first ? acClass.second : NULL,
383 acComp.first ? acComp.second : NULL,
384 nidFormat.first ? nidFormat.second : NULL,
385 spQual.first ? spQual.second : NULL,
390 // Since we're not passing by index, we need to fully compute the return URL and binding.
391 // Compute the ACS URL. We add the ACS location to the base handlerURL.
392 prop = ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
394 ACSloc += prop.second;
397 // We may already have RelayState set if we looped back here,
398 // but we've turned it back into a resource by this point, so if there's
399 // a target on the URL, reset to that value.
400 prop.second = request.getParameter("target");
401 if (prop.second && *prop.second)
402 target = prop.second;
406 app, &request, request, entityID.c_str(),
408 ACS ? XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT) : false,
409 ACSloc.c_str(), ACS ? ACS->getXMLString("Binding").second : NULL,
410 isPassive, forceAuthn,
411 acClass.first ? acClass.second : NULL,
412 acComp.first ? acComp.second : NULL,
413 nidFormat.first ? nidFormat.second : NULL,
414 spQual.first ? spQual.second : NULL,
420 DDF out,in = DDF(m_address.c_str()).structure();
421 DDFJanitor jin(in), jout(out);
422 in.addmember("application_id").string(app.getId());
423 if (!entityID.empty())
424 in.addmember("entity_id").string(entityID.c_str());
426 in.addmember("isPassive").integer(1);
428 in.addmember("forceAuthn").integer(1);
430 in.addmember("authnContextClassRef").string(acClass.second);
432 in.addmember("authnContextComparison").string(acComp.second);
434 in.addmember("NameIDFormat").string(nidFormat.second);
436 in.addmember("SPNameQualifier").string(spQual.second);
437 if (acsByIndex.first && acsByIndex.second) {
439 // Determine index to use.
440 pair<bool,const char*> ix = pair<bool,const char*>(false,NULL);
441 if (!strncmp(ACSloc.c_str(), "https", 5)) {
442 ix = ACS->getString("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
444 ix = ACS->getString("index");
447 ix = ACS->getString("index");
449 in.addmember("acsIndex").string(ix.second);
450 if (XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT))
451 in.addmember("artifact").integer(1);
455 // Since we're not passing by index, we need to fully compute the return URL and binding.
456 // Compute the ACS URL. We add the ACS location to the base handlerURL.
457 prop = ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
459 ACSloc += prop.second;
460 in.addmember("acsLocation").string(ACSloc.c_str());
462 prop = ACS->getString("Binding");
463 in.addmember("acsBinding").string(prop.second);
464 if (XMLString::equals(prop.second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT))
465 in.addmember("artifact").integer(1);
470 // We may already have RelayState set if we looped back here,
471 // but we've turned it back into a resource by this point, so if there's
472 // a target on the URL, reset to that value.
473 prop.second = request.getParameter("target");
474 if (prop.second && *prop.second)
475 target = prop.second;
478 in.addmember("RelayState").unsafe_string(target.c_str());
480 // Remote the processing.
481 out = request.getServiceProvider().getListenerService()->send(in);
482 return unwrap(request, out);
485 pair<bool,long> SAML2SessionInitiator::unwrap(SPRequest& request, DDF& out) const
487 // See if there's any response to send back.
488 if (!out["redirect"].isnull() || !out["response"].isnull()) {
489 // If so, we're responsible for handling the POST data, probably by dropping a cookie.
490 preservePostData(request.getApplication(), request, request, out["RelayState"].string());
492 return RemotedHandler::unwrap(request, out);
495 void SAML2SessionInitiator::receive(DDF& in, ostream& out)
498 const char* aid=in["application_id"].string();
499 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
501 // Something's horribly wrong.
502 m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
503 throw ConfigurationException("Unable to locate application for new session, deleted?");
507 DDFJanitor jout(ret);
509 // Wrap the outgoing object with a Response facade.
510 auto_ptr<HTTPResponse> http(getResponse(ret));
512 auto_ptr_XMLCh index(in["acsIndex"].string());
513 auto_ptr_XMLCh bind(in["acsBinding"].string());
515 string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
516 string postData(in["PostData"].string() ? in["PostData"].string() : "");
518 // Since we're remoted, the result should either be a throw, which we pass on,
519 // a false/0 return, which we just return as an empty structure, or a response/redirect,
520 // which we capture in the facade and send back.
522 *app, NULL, *http.get(), in["entity_id"].string(),
524 (in["artifact"].integer() != 0),
525 in["acsLocation"].string(), bind.get(),
526 in["isPassive"].integer()==1, in["forceAuthn"].integer()==1,
527 in["authnContextClassRef"].string(), in["authnContextComparison"].string(),
528 in["NameIDFormat"].string(), in["SPNameQualifier"].string(),
533 ret.addmember("RelayState").unsafe_string(relayState.c_str());
539 class _sameIdP : public binary_function<const IDPEntry*, const XMLCh*, bool>
542 bool operator()(const IDPEntry* entry, const XMLCh* entityID) const {
543 return entry ? XMLString::equals(entry->getProviderID(), entityID) : false;
549 pair<bool,long> SAML2SessionInitiator::doRequest(
550 const Application& app,
551 const HTTPRequest* httpRequest,
552 HTTPResponse& httpResponse,
553 const char* entityID,
554 const XMLCh* acsIndex,
555 bool artifactInbound,
556 const char* acsLocation,
557 const XMLCh* acsBinding,
560 const char* authnContextClassRef,
561 const char* authnContextComparison,
562 const char* NameIDFormat,
563 const char* SPNameQualifier,
568 bool ECP = XMLString::equals(acsBinding, m_paosBinding.get());
570 pair<const EntityDescriptor*,const RoleDescriptor*> entity = pair<const EntityDescriptor*,const RoleDescriptor*>(NULL,NULL);
571 const IDPSSODescriptor* role = NULL;
572 const EndpointType* ep = NULL;
573 const MessageEncoder* encoder = NULL;
575 // We won't need this for ECP, but safety dictates we get the lock here.
576 MetadataProvider* m=app.getMetadataProvider();
582 m_log.error("MessageEncoder for PAOS binding not available");
583 return make_pair(false,0L);
587 // Use metadata to locate the IdP's SSO service.
588 MetadataProviderCriteria mc(app, entityID, &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
589 entity=m->getEntityDescriptor(mc);
591 m_log.warn("unable to locate metadata for provider (%s)", entityID);
592 throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
594 else if (!entity.second) {
595 m_log.log(getParent() ? Priority::INFO : Priority::WARN, "unable to locate SAML 2.0 identity provider role for provider (%s)", entityID);
597 return make_pair(false,0L);
598 throw MetadataException("Unable to locate SAML 2.0 identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
600 else if (artifactInbound && !SPConfig::getConfig().getArtifactResolver()->isSupported(dynamic_cast<const SSODescriptorType&>(*entity.second))) {
601 m_log.warn("artifact binding selected for response, but identity provider lacks support");
603 return make_pair(false,0L);
604 throw MetadataException("Identity provider ($entityID) lacks SAML 2.0 artifact support.", namedparams(1, "entityID", entityID));
607 // Loop over the supportable outgoing bindings.
608 role = dynamic_cast<const IDPSSODescriptor*>(entity.second);
609 vector<const XMLCh*>::const_iterator b;
610 for (b = m_bindings.begin(); b!=m_bindings.end(); ++b) {
611 if (ep=EndpointManager<SingleSignOnService>(role->getSingleSignOnServices()).getByBinding(*b)) {
612 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
613 if (enc!=m_encoders.end())
614 encoder = enc->second;
618 if (!ep || !encoder) {
619 m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
621 return make_pair(false,0L);
622 throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
626 preserveRelayState(app, httpResponse, relayState);
628 auto_ptr<AuthnRequest> req(m_requestTemplate ? m_requestTemplate->cloneAuthnRequest() : AuthnRequestBuilder::buildAuthnRequest());
629 if (m_requestTemplate) {
630 // Freshen TS and ID.
632 req->setIssueInstant(time(NULL));
636 req->setDestination(ep->getLocation());
637 if (acsIndex && *acsIndex)
638 req->setAssertionConsumerServiceIndex(acsIndex);
640 auto_ptr_XMLCh wideloc(acsLocation);
641 req->setAssertionConsumerServiceURL(wideloc.get());
643 if (acsBinding && *acsBinding)
644 req->setProtocolBinding(acsBinding);
646 req->IsPassive(isPassive);
648 req->ForceAuthn(forceAuthn);
649 if (!req->getIssuer()) {
650 Issuer* issuer = IssuerBuilder::buildIssuer();
651 req->setIssuer(issuer);
652 issuer->setName(app.getRelyingParty(entity.first)->getXMLString("entityID").second);
654 if (!req->getNameIDPolicy()) {
655 NameIDPolicy* namepol = NameIDPolicyBuilder::buildNameIDPolicy();
656 req->setNameIDPolicy(namepol);
657 namepol->AllowCreate(true);
659 if (NameIDFormat && *NameIDFormat) {
660 auto_ptr_XMLCh wideform(NameIDFormat);
661 req->getNameIDPolicy()->setFormat(wideform.get());
663 if (SPNameQualifier && *SPNameQualifier) {
664 auto_ptr_XMLCh widequal(SPNameQualifier);
665 req->getNameIDPolicy()->setSPNameQualifier(widequal.get());
667 if (authnContextClassRef || authnContextComparison) {
668 RequestedAuthnContext* reqContext = req->getRequestedAuthnContext();
670 reqContext = RequestedAuthnContextBuilder::buildRequestedAuthnContext();
671 req->setRequestedAuthnContext(reqContext);
673 if (authnContextClassRef) {
674 reqContext->getAuthnContextDeclRefs().clear();
675 auto_ptr_XMLCh wideclass(authnContextClassRef);
676 AuthnContextClassRef* cref = AuthnContextClassRefBuilder::buildAuthnContextClassRef();
677 cref->setReference(wideclass.get());
678 reqContext->getAuthnContextClassRefs().push_back(cref);
681 if (reqContext->getAuthnContextClassRefs().empty() && reqContext->getAuthnContextDeclRefs().empty()) {
682 req->setRequestedAuthnContext(NULL);
684 else if (authnContextComparison) {
685 auto_ptr_XMLCh widecomp(authnContextComparison);
686 reqContext->setComparison(widecomp.get());
690 pair<bool,bool> requestDelegation = getBool("requestDelegation");
691 if (requestDelegation.first && requestDelegation.second && entity.first) {
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(NULL) + 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 if (ECP && entityID) {
709 auto_ptr_XMLCh wideid(entityID);
710 Scoping* scoping = req->getScoping();
712 scoping = ScopingBuilder::buildScoping();
713 req->setScoping(scoping);
715 IDPList* idplist = scoping->getIDPList();
717 idplist = IDPListBuilder::buildIDPList();
718 scoping->setIDPList(idplist);
720 VectorOf(IDPEntry) entries = idplist->getIDPEntrys();
721 if (find_if(entries, bind2nd(_sameIdP(), wideid.get())) == NULL) {
722 IDPEntry* entry = IDPEntryBuilder::buildIDPEntry();
723 entry->setProviderID(wideid.get());
724 entries.push_back(entry);
728 auto_ptr_char dest(ep ? ep->getLocation() : NULL);
731 // If the request object is available, we're responsible for the POST data.
732 preservePostData(app, *httpRequest, httpResponse, relayState.c_str());
735 long ret = sendMessage(
736 *encoder, req.get(), relayState.c_str(), dest.get(), role, app, httpResponse, role ? role->WantAuthnRequestsSigned() : false
738 req.release(); // freed by encoder
739 return make_pair(true,ret);
741 return make_pair(false,0L);