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