Adding capability to save and restore posted data through login loop
[shibboleth/cpp-sp.git] / shibsp / handler / impl / SAML2SessionInitiator.cpp
1 /*
2  *  Copyright 2001-2009 Internet2
3  *
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 /**
18  * SAML2SessionInitiator.cpp
19  *
20  * SAML 2.0 AuthnRequest support.
21  */
22
23 #include "internal.h"
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"
32
33 #ifndef SHIBSP_LITE
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 using namespace opensaml::saml2;
41 using namespace opensaml::saml2p;
42 using namespace opensaml::saml2md;
43 #else
44 #include <xercesc/util/XMLUniDefs.hpp>
45 #endif
46
47 using namespace shibsp;
48 using namespace opensaml;
49 using namespace xmltooling;
50 using namespace std;
51
52 namespace shibsp {
53
54 #if defined (_MSC_VER)
55     #pragma warning( push )
56     #pragma warning( disable : 4250 )
57 #endif
58
59     class SHIBSP_DLLLOCAL SAML2SessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
60     {
61     public:
62         SAML2SessionInitiator(const DOMElement* e, const char* appId);
63         virtual ~SAML2SessionInitiator() {
64 #ifndef SHIBSP_LITE
65             if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
66                 XMLString::release(&m_outgoing);
67                 for_each(m_encoders.begin(), m_encoders.end(), cleanup_pair<const XMLCh*,MessageEncoder>());
68                 delete m_requestTemplate;
69                 delete m_ecp;
70             }
71 #endif
72         }
73
74         void setParent(const PropertySet* parent);
75         void receive(DDF& in, ostream& out);
76         pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
77
78     private:
79         pair<bool,long> doRequest(
80             const Application& application,
81             HTTPResponse& httpResponse,
82             const char* entityID,
83             const XMLCh* acsIndex,
84             bool artifactInbound,
85             const char* acsLocation,
86             const XMLCh* acsBinding,
87             bool isPassive,
88             bool forceAuthn,
89             const char* authnContextClassRef,
90             const char* authnContextComparison,
91             string& relayState,
92             string& postData
93             ) const;
94
95         string m_appId;
96         auto_ptr_char m_paosNS,m_ecpNS;
97         auto_ptr_XMLCh m_paosBinding;
98 #ifndef SHIBSP_LITE
99         XMLCh* m_outgoing;
100         vector<const XMLCh*> m_bindings;
101         map<const XMLCh*,MessageEncoder*> m_encoders;
102         MessageEncoder* m_ecp;
103         AuthnRequest* m_requestTemplate;
104 #else
105         bool m_ecp;
106 #endif
107     };
108
109 #if defined (_MSC_VER)
110     #pragma warning( pop )
111 #endif
112
113     SessionInitiator* SHIBSP_DLLLOCAL SAML2SessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
114     {
115         return new SAML2SessionInitiator(p.first, p.second);
116     }
117
118 };
119
120 SAML2SessionInitiator::SAML2SessionInitiator(const DOMElement* e, const char* appId)
121     : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.SAML2")), m_appId(appId),
122         m_paosNS(samlconstants::PAOS_NS), m_ecpNS(samlconstants::SAML20ECP_NS), m_paosBinding(samlconstants::SAML20_BINDING_PAOS)
123 {
124     static const XMLCh ECP[] = UNICODE_LITERAL_3(E,C,P);
125     const XMLCh* flag = e ? e->getAttributeNS(NULL,ECP) : NULL;
126 #ifdef SHIBSP_LITE
127     m_ecp = (flag && (*flag == chLatin_t || *flag == chDigit_1));
128 #else
129     m_outgoing=NULL;
130     m_ecp = NULL;
131     m_requestTemplate=NULL;
132
133     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
134         // Check for a template AuthnRequest to build from.
135         DOMElement* child = XMLHelper::getFirstChildElement(e, samlconstants::SAML20P_NS, AuthnRequest::LOCAL_NAME);
136         if (child)
137             m_requestTemplate = dynamic_cast<AuthnRequest*>(AuthnRequestBuilder::buildOneFromElement(child));
138
139         // If directed, build an ECP encoder.
140         if (flag && (*flag == chLatin_t || *flag == chDigit_1)) {
141             try {
142                 m_ecp = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
143                     samlconstants::SAML20_BINDING_PAOS, pair<const DOMElement*,const XMLCh*>(e,NULL)
144                     );
145             }
146             catch (exception& ex) {
147                 m_log.error("error building PAOS/ECP MessageEncoder: %s", ex.what());
148             }
149         }
150
151         // Handle outgoing binding setup.
152         pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings");
153         if (outgoing.first) {
154             m_outgoing = XMLString::replicate(outgoing.second);
155             XMLString::trim(m_outgoing);
156         }
157         else {
158             // No override, so we'll install a default binding precedence.
159             string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
160                 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
161             m_outgoing = XMLString::transcode(prec.c_str());
162         }
163
164         int pos;
165         XMLCh* start = m_outgoing;
166         while (start && *start) {
167             pos = XMLString::indexOf(start,chSpace);
168             if (pos != -1)
169                 *(start + pos)=chNull;
170             m_bindings.push_back(start);
171             try {
172                 auto_ptr_char b(start);
173                 MessageEncoder * encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
174                     b.get(),pair<const DOMElement*,const XMLCh*>(e,NULL)
175                     );
176                 m_encoders[start] = encoder;
177                 m_log.debug("supporting outgoing binding (%s)", b.get());
178             }
179             catch (exception& ex) {
180                 m_log.error("error building MessageEncoder: %s", ex.what());
181             }
182             if (pos != -1)
183                 start = start + pos + 1;
184             else
185                 break;
186         }
187     }
188 #endif
189
190     // If Location isn't set, defer address registration until the setParent call.
191     pair<bool,const char*> loc = getString("Location");
192     if (loc.first) {
193         string address = m_appId + loc.second + "::run::SAML2SI";
194         setAddress(address.c_str());
195     }
196 }
197
198 void SAML2SessionInitiator::setParent(const PropertySet* parent)
199 {
200     DOMPropertySet::setParent(parent);
201     pair<bool,const char*> loc = getString("Location");
202     if (loc.first) {
203         string address = m_appId + loc.second + "::run::SAML2SI";
204         setAddress(address.c_str());
205     }
206     else {
207         m_log.warn("no Location property in SAML2 SessionInitiator (or parent), can't register as remoted handler");
208     }
209 }
210
211 pair<bool,long> SAML2SessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
212 {
213     // First check for ECP support, since that doesn't require an IdP to be known.
214     bool ECP = false;
215     if (m_ecp && request.getHeader("Accept").find("application/vnd.paos+xml") != string::npos) {
216         string PAOS = request.getHeader("PAOS");
217         if (PAOS.find(m_paosNS.get()) != string::npos && PAOS.find(m_ecpNS.get()) != string::npos)
218             ECP = true;
219     }
220
221     // We have to know the IdP to function unless this is ECP.
222     if (!ECP && (entityID.empty()))
223         return make_pair(false,0L);
224
225     string target;
226     string postData;
227     const Handler* ACS=NULL;
228     const char* option;
229     pair<bool,const char*> acClass;
230     pair<bool,const char*> acComp;
231     bool isPassive=false,forceAuthn=false;
232     const Application& app=request.getApplication();
233
234     // ECP means the ACS will be by value no matter what.
235     pair<bool,bool> acsByIndex = ECP ? make_pair(true,false) : getBool("acsByIndex");
236
237     if (isHandler) {
238         option=request.getParameter("acsIndex");
239         if (option) {
240             ACS = app.getAssertionConsumerServiceByIndex(atoi(option));
241             if (!ACS)
242                 request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using default ACS location");
243             else if (ECP && !XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_PAOS)) {
244                 request.log(SPRequest::SPWarn, "acsIndex in request referenced a non-PAOS ACS, using default ACS location");
245                 ACS = NULL;
246             }
247         }
248
249         option = request.getParameter("target");
250         if (option)
251             target = option;
252
253         // Always need to recover target URL to compute handler below.
254         // don't think we need to recover post data here though
255         recoverRelayState(request.getApplication(), request, request, target, false);
256
257         pair<bool,bool> flag;
258         option = request.getParameter("isPassive");
259         if (option) {
260             isPassive = (*option=='1' || *option=='t');
261         }
262         else {
263             flag = getBool("isPassive");
264             isPassive = (flag.first && flag.second);
265         }
266         if (!isPassive) {
267             option = request.getParameter("forceAuthn");
268             if (option) {
269                 forceAuthn = (*option=='1' || *option=='t');
270             }
271             else {
272                 flag = getBool("forceAuthn");
273                 forceAuthn = (flag.first && flag.second);
274             }
275         }
276
277         if (acClass.second = request.getParameter("authnContextClassRef"))
278             acClass.first = true;
279         else
280             acClass = getString("authnContextClassRef");
281
282         if (acComp.second = request.getParameter("authnContextComparison"))
283             acComp.first = true;
284         else
285             acComp = getString("authnContextComparison");
286     }
287     else {
288         // We're running as a "virtual handler" from within the filter.
289         // The target resource is the current one and everything else is defaulted.
290         target=request.getRequestURL();
291         postData = getPostData(request);
292         const PropertySet* settings = request.getRequestSettings().first;
293
294         pair<bool,bool> flag = settings->getBool("isPassive");
295         if (!flag.first)
296             flag = getBool("isPassive");
297         isPassive = flag.first && flag.second;
298         if (!isPassive) {
299             flag = settings->getBool("forceAuthn");
300             if (!flag.first)
301                 flag = getBool("forceAuthn");
302             forceAuthn = flag.first && flag.second;
303         }
304
305         acClass = settings->getString("authnContextClassRef");
306         if (!acClass.first)
307             acClass = getString("authnContextClassRef");
308         acComp = settings->getString("authnContextComparison");
309         if (!acComp.first)
310             acComp = getString("authnContextComparison");
311     }
312
313     if (ECP)
314         m_log.debug("attempting to initiate session using SAML 2.0 Enhanced Client Profile");
315     else
316         m_log.debug("attempting to initiate session using SAML 2.0 with provider (%s)", entityID.c_str());
317
318     if (!ACS) {
319         if (ECP) {
320             const vector<const Handler*>& handlers = app.getAssertionConsumerServicesByBinding(m_paosBinding.get());
321             if (handlers.empty())
322                 throw ConfigurationException("Unable to locate PAOS response endpoint.");
323             ACS = handlers.front();
324         }
325         else {
326             pair<bool,unsigned int> index = getUnsignedInt("defaultACSIndex");
327             if (index.first) {
328                 ACS = app.getAssertionConsumerServiceByIndex(index.second);
329                 if (!ACS)
330                     request.log(SPRequest::SPWarn, "invalid defaultACSIndex, using default ACS location");
331             }
332             if (!ACS)
333                 ACS = app.getDefaultAssertionConsumerService();
334         }
335     }
336
337     // To invoke the request builder, the key requirement is to figure out how
338     // to express the ACS, by index or value, and if by value, where.
339     // We have to compute the handlerURL no matter what, because we may need to
340     // flip the index to an SSL-version.
341     string ACSloc=request.getHandlerURL(target.c_str());
342
343     SPConfig& conf = SPConfig::getConfig();
344     if (conf.isEnabled(SPConfig::OutOfProcess)) {
345         if (!acsByIndex.first || acsByIndex.second) {
346             // Pass by Index.
347             if (isHandler) {
348                 // We may already have RelayState set if we looped back here,
349                 // but just in case target is a resource, we reset it back.
350                 target.erase();
351                 option = request.getParameter("target");
352                 if (option)
353                     target = option;
354             }
355
356             // Determine index to use.
357             pair<bool,const XMLCh*> ix = pair<bool,const XMLCh*>(false,NULL);
358             if (ACS) {
359                 if (!strncmp(ACSloc.c_str(), "https", 5)) {
360                         ix = ACS->getXMLString("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
361                         if (!ix.first)
362                                 ix = ACS->getXMLString("index");
363                 }
364                 else {
365                         ix = ACS->getXMLString("index");
366                 }
367             }
368
369             return doRequest(
370                 app, request, entityID.c_str(),
371                 ix.second,
372                 ACS ? XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT) : false,
373                 NULL, NULL,
374                 isPassive, forceAuthn,
375                 acClass.first ? acClass.second : NULL,
376                 acComp.first ? acComp.second : NULL,
377                 target,
378                 postData
379                 );
380         }
381
382         // Since we're not passing by index, we need to fully compute the return URL and binding.
383         // Compute the ACS URL. We add the ACS location to the base handlerURL.
384         pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
385         if (loc.first) ACSloc+=loc.second;
386
387         if (isHandler) {
388             // We may already have RelayState set if we looped back here,
389             // but just in case target is a resource, we reset it back.
390             target.erase();
391             option = request.getParameter("target");
392             if (option)
393                 target = option;
394         }
395
396         return doRequest(
397             app, request, entityID.c_str(),
398             NULL,
399             ACS ? XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT) : false,
400             ACSloc.c_str(), ACS ? ACS->getXMLString("Binding").second : NULL,
401             isPassive, forceAuthn,
402             acClass.first ? acClass.second : NULL,
403             acComp.first ? acComp.second : NULL,
404             target,
405             postData
406             );
407     }
408
409     // Remote the call.
410     DDF out,in = DDF(m_address.c_str()).structure();
411     DDFJanitor jin(in), jout(out);
412     in.addmember("application_id").string(app.getId());
413     if (!entityID.empty())
414         in.addmember("entity_id").string(entityID.c_str());
415     if (isPassive)
416         in.addmember("isPassive").integer(1);
417     else if (forceAuthn)
418         in.addmember("forceAuthn").integer(1);
419     if (acClass.first)
420         in.addmember("authnContextClassRef").string(acClass.second);
421     if (acComp.first)
422         in.addmember("authnContextComparison").string(acComp.second);
423     if (!acsByIndex.first || acsByIndex.second) {
424         if (ACS) {
425             // Determine index to use.
426             pair<bool,const char*> ix = pair<bool,const char*>(false,NULL);
427                 if (!strncmp(ACSloc.c_str(), "https", 5)) {
428                         ix = ACS->getString("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
429                         if (!ix.first)
430                                 ix = ACS->getString("index");
431                 }
432                 else {
433                         ix = ACS->getString("index");
434                 }
435             in.addmember("acsIndex").string(ix.second);
436             if (XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT))
437                 in.addmember("artifact").integer(1);
438         }
439     }
440     else {
441         // Since we're not passing by index, we need to fully compute the return URL and binding.
442         // Compute the ACS URL. We add the ACS location to the base handlerURL.
443         pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
444         if (loc.first) ACSloc+=loc.second;
445         in.addmember("acsLocation").string(ACSloc.c_str());
446         if (ACS) {
447             loc = ACS->getString("Binding");
448             in.addmember("acsBinding").string(loc.second);
449             if (XMLString::equals(loc.second, samlconstants::SAML20_BINDING_HTTP_ARTIFACT))
450                 in.addmember("artifact").integer(1);
451         }
452     }
453
454     if (isHandler) {
455         // We may already have RelayState set if we looped back here,
456         // but just in case target is a resource, we reset it back.
457         target.erase();
458         option = request.getParameter("target");
459         if (option)
460             target = option;
461     }
462     if (!target.empty())
463         in.addmember("RelayState").string(target.c_str());
464
465     if (!postData.empty()) {
466         in.addmember("PostData").string(postData.c_str());
467         m_log.debug("saml2SI remoting %d posted bytes", postData.length());
468     }
469
470     // Remote the processing.
471     out = request.getServiceProvider().getListenerService()->send(in);
472     return unwrap(request, out);
473 }
474
475 void SAML2SessionInitiator::receive(DDF& in, ostream& out)
476 {
477     // Find application.
478     const char* aid=in["application_id"].string();
479     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
480     if (!app) {
481         // Something's horribly wrong.
482         m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
483         throw ConfigurationException("Unable to locate application for new session, deleted?");
484     }
485
486     DDF ret(NULL);
487     DDFJanitor jout(ret);
488
489     // Wrap the outgoing object with a Response facade.
490     auto_ptr<HTTPResponse> http(getResponse(ret));
491
492     auto_ptr_XMLCh index(in["acsIndex"].string());
493     auto_ptr_XMLCh bind(in["acsBinding"].string());
494
495     string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
496     string postData(in["PostData"].string() ? in["PostData"].string() : "");
497
498     // Since we're remoted, the result should either be a throw, which we pass on,
499     // a false/0 return, which we just return as an empty structure, or a response/redirect,
500     // which we capture in the facade and send back.
501     doRequest(
502         *app, *http.get(), in["entity_id"].string(),
503         index.get(),
504         (in["artifact"].integer() != 0),
505         in["acsLocation"].string(), bind.get(),
506         in["isPassive"].integer()==1, in["forceAuthn"].integer()==1,
507         in["authnContextClassRef"].string(), in["authnContextComparison"].string(),
508         relayState,
509         postData
510         );
511     out << ret;
512 }
513
514 #ifndef SHIBSP_LITE
515 namespace {
516     class _sameIdP : public binary_function<const IDPEntry*, const XMLCh*, bool>
517     {
518     public:
519         bool operator()(const IDPEntry* entry, const XMLCh* entityID) const {
520             return entry ? XMLString::equals(entry->getProviderID(), entityID) : false;
521         }
522     };
523 };
524 #endif
525
526 pair<bool,long> SAML2SessionInitiator::doRequest(
527     const Application& app,
528     HTTPResponse& httpResponse,
529     const char* entityID,
530     const XMLCh* acsIndex,
531     bool artifactInbound,
532     const char* acsLocation,
533     const XMLCh* acsBinding,
534     bool isPassive,
535     bool forceAuthn,
536     const char* authnContextClassRef,
537     const char* authnContextComparison,
538     string& relayState,
539     string& postData
540     ) const
541 {
542 #ifndef SHIBSP_LITE
543     bool ECP = XMLString::equals(acsBinding, m_paosBinding.get());
544
545     pair<const EntityDescriptor*,const RoleDescriptor*> entity = pair<const EntityDescriptor*,const RoleDescriptor*>(NULL,NULL);
546     const IDPSSODescriptor* role = NULL;
547     const EndpointType* ep = NULL;
548     const MessageEncoder* encoder = NULL;
549
550     // We won't need this for ECP, but safety dictates we get the lock here.
551     MetadataProvider* m=app.getMetadataProvider();
552     Locker locker(m);
553
554     if (ECP) {
555         encoder = m_ecp;
556         if (!encoder) {
557             m_log.error("MessageEncoder for PAOS binding not available");
558             return make_pair(false,0L);
559         }
560     }
561     else {
562         // Use metadata to locate the IdP's SSO service.
563         MetadataProviderCriteria mc(app, entityID, &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
564         entity=m->getEntityDescriptor(mc);
565         if (!entity.first) {
566             m_log.warn("unable to locate metadata for provider (%s)", entityID);
567             throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
568         }
569         else if (!entity.second) {
570             m_log.warn("unable to locate SAML 2.0 identity provider role for provider (%s)", entityID);
571             if (getParent())
572                 return make_pair(false,0L);
573             throw MetadataException("Unable to locate SAML 2.0 identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
574         }
575         else if (artifactInbound && !SPConfig::getConfig().getArtifactResolver()->isSupported(dynamic_cast<const SSODescriptorType&>(*entity.second))) {
576             m_log.warn("artifact binding selected for response, but identity provider lacks support");
577             if (getParent())
578                 return make_pair(false,0L);
579             throw MetadataException("Identity provider ($entityID) lacks SAML 2.0 artifact support.", namedparams(1, "entityID", entityID));
580         }
581
582         // Loop over the supportable outgoing bindings.
583         role = dynamic_cast<const IDPSSODescriptor*>(entity.second);
584         vector<const XMLCh*>::const_iterator b;
585         for (b = m_bindings.begin(); b!=m_bindings.end(); ++b) {
586             if (ep=EndpointManager<SingleSignOnService>(role->getSingleSignOnServices()).getByBinding(*b)) {
587                 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
588                 if (enc!=m_encoders.end())
589                     encoder = enc->second;
590                 break;
591             }
592         }
593         if (!ep || !encoder) {
594             m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
595             if (getParent())
596                 return make_pair(false,0L);
597             throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
598         }
599     }
600
601     preserveRelayState(app, httpResponse, relayState);
602     preservePostData(app, httpResponse, postData, relayState);
603
604     auto_ptr<AuthnRequest> req(m_requestTemplate ? m_requestTemplate->cloneAuthnRequest() : AuthnRequestBuilder::buildAuthnRequest());
605     if (m_requestTemplate) {
606         // Freshen TS and ID.
607         req->setID(NULL);
608         req->setIssueInstant(time(NULL));
609     }
610
611     if (ep)
612         req->setDestination(ep->getLocation());
613     if (acsIndex && *acsIndex)
614         req->setAssertionConsumerServiceIndex(acsIndex);
615     if (acsLocation) {
616         auto_ptr_XMLCh wideloc(acsLocation);
617         req->setAssertionConsumerServiceURL(wideloc.get());
618     }
619     if (acsBinding && *acsBinding)
620         req->setProtocolBinding(acsBinding);
621     if (isPassive)
622         req->IsPassive(isPassive);
623     else if (forceAuthn)
624         req->ForceAuthn(forceAuthn);
625     if (!req->getIssuer()) {
626         Issuer* issuer = IssuerBuilder::buildIssuer();
627         req->setIssuer(issuer);
628         issuer->setName(app.getRelyingParty(entity.first)->getXMLString("entityID").second);
629     }
630     if (!req->getNameIDPolicy()) {
631         NameIDPolicy* namepol = NameIDPolicyBuilder::buildNameIDPolicy();
632         req->setNameIDPolicy(namepol);
633         namepol->AllowCreate(true);
634     }
635     if (authnContextClassRef || authnContextComparison) {
636         RequestedAuthnContext* reqContext = req->getRequestedAuthnContext();
637         if (!reqContext) {
638             reqContext = RequestedAuthnContextBuilder::buildRequestedAuthnContext();
639             req->setRequestedAuthnContext(reqContext);
640         }
641         if (authnContextClassRef) {
642             reqContext->getAuthnContextDeclRefs().clear();
643             auto_ptr_XMLCh wideclass(authnContextClassRef);
644             AuthnContextClassRef* cref = AuthnContextClassRefBuilder::buildAuthnContextClassRef();
645             cref->setReference(wideclass.get());
646             reqContext->getAuthnContextClassRefs().push_back(cref);
647         }
648
649         if (reqContext->getAuthnContextClassRefs().empty() && reqContext->getAuthnContextDeclRefs().empty()) {
650                 req->setRequestedAuthnContext(NULL);
651         }
652         else if (authnContextComparison) {
653             auto_ptr_XMLCh widecomp(authnContextComparison);
654             reqContext->setComparison(widecomp.get());
655         }
656     }
657
658     if (ECP && entityID) {
659         auto_ptr_XMLCh wideid(entityID);
660         Scoping* scoping = req->getScoping();
661         if (!scoping) {
662             scoping = ScopingBuilder::buildScoping();
663             req->setScoping(scoping);
664         }
665         IDPList* idplist = scoping->getIDPList();
666         if (!idplist) {
667             idplist = IDPListBuilder::buildIDPList();
668             scoping->setIDPList(idplist);
669         }
670         VectorOf(IDPEntry) entries = idplist->getIDPEntrys();
671         if (find_if(entries, bind2nd(_sameIdP(), wideid.get())) == NULL) {
672             IDPEntry* entry = IDPEntryBuilder::buildIDPEntry();
673             entry->setProviderID(wideid.get());
674             entries.push_back(entry);
675         }
676     }
677
678     auto_ptr_char dest(ep ? ep->getLocation() : NULL);
679
680     long ret = sendMessage(
681         *encoder, req.get(), relayState.c_str(), dest.get(), role, app, httpResponse, role ? role->WantAuthnRequestsSigned() : false
682         );
683     req.release();  // freed by encoder
684     return make_pair(true,ret);
685 #else
686     return make_pair(false,0L);
687 #endif
688 }