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