0a0aea61cfb42152f67194aecb46f3afcfb6c8b8
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml2 / SSOProfileHandler.java
1 /*
2  * Copyright [2007] [University Corporation for Advanced Internet Development, Inc.]
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 package edu.internet2.middleware.shibboleth.idp.profile.saml2;
18
19 import java.io.IOException;
20 import java.util.ArrayList;
21
22 import javax.servlet.RequestDispatcher;
23 import javax.servlet.ServletException;
24 import javax.servlet.http.HttpServletRequest;
25
26 import org.opensaml.common.SAMLObjectBuilder;
27 import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
28 import org.opensaml.common.xml.SAMLConstants;
29 import org.opensaml.saml2.binding.AuthnResponseEndpointSelector;
30 import org.opensaml.saml2.core.AttributeStatement;
31 import org.opensaml.saml2.core.AuthnContext;
32 import org.opensaml.saml2.core.AuthnContextClassRef;
33 import org.opensaml.saml2.core.AuthnContextDeclRef;
34 import org.opensaml.saml2.core.AuthnRequest;
35 import org.opensaml.saml2.core.AuthnStatement;
36 import org.opensaml.saml2.core.RequestedAuthnContext;
37 import org.opensaml.saml2.core.Response;
38 import org.opensaml.saml2.core.Statement;
39 import org.opensaml.saml2.core.StatusCode;
40 import org.opensaml.saml2.core.Subject;
41 import org.opensaml.saml2.core.SubjectLocality;
42 import org.opensaml.saml2.metadata.AssertionConsumerService;
43 import org.opensaml.saml2.metadata.Endpoint;
44 import org.opensaml.saml2.metadata.EntityDescriptor;
45 import org.opensaml.saml2.metadata.IDPSSODescriptor;
46 import org.opensaml.saml2.metadata.SPSSODescriptor;
47 import org.opensaml.ws.message.decoder.MessageDecodingException;
48 import org.opensaml.ws.transport.http.HTTPInTransport;
49 import org.opensaml.ws.transport.http.HTTPOutTransport;
50 import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
51 import org.opensaml.ws.transport.http.HttpServletResponseAdapter;
52 import org.opensaml.xml.io.MarshallingException;
53 import org.opensaml.xml.io.UnmarshallingException;
54 import org.opensaml.xml.security.SecurityException;
55 import org.opensaml.xml.util.DatatypeHelper;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
60 import edu.internet2.middleware.shibboleth.common.profile.provider.BaseSAMLProfileRequestContext;
61 import edu.internet2.middleware.shibboleth.common.relyingparty.ProfileConfiguration;
62 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
63 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.SSOConfiguration;
64 import edu.internet2.middleware.shibboleth.common.util.HttpHelper;
65 import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
66 import edu.internet2.middleware.shibboleth.idp.authn.PassiveAuthenticationException;
67 import edu.internet2.middleware.shibboleth.idp.authn.Saml2LoginContext;
68 import edu.internet2.middleware.shibboleth.idp.session.Session;
69
70 /** SAML 2.0 SSO request profile handler. */
71 public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
72
73     /** Class logger. */
74     private final Logger log = LoggerFactory.getLogger(SSOProfileHandler.class);
75
76     /** Builder of AuthnStatement objects. */
77     private SAMLObjectBuilder<AuthnStatement> authnStatementBuilder;
78
79     /** Builder of AuthnContext objects. */
80     private SAMLObjectBuilder<AuthnContext> authnContextBuilder;
81
82     /** Builder of AuthnContextClassRef objects. */
83     private SAMLObjectBuilder<AuthnContextClassRef> authnContextClassRefBuilder;
84
85     /** Builder of AuthnContextDeclRef objects. */
86     private SAMLObjectBuilder<AuthnContextDeclRef> authnContextDeclRefBuilder;
87
88     /** Builder of SubjectLocality objects. */
89     private SAMLObjectBuilder<SubjectLocality> subjectLocalityBuilder;
90
91     /** Builder of Endpoint objects. */
92     private SAMLObjectBuilder<Endpoint> endpointBuilder;
93
94     /** URL of the authentication manager servlet. */
95     private String authenticationManagerPath;
96
97     /**
98      * Constructor.
99      * 
100      * @param authnManagerPath path to the authentication manager servlet
101      */
102     @SuppressWarnings("unchecked")
103     public SSOProfileHandler(String authnManagerPath) {
104         super();
105
106         authenticationManagerPath = authnManagerPath;
107
108         authnStatementBuilder = (SAMLObjectBuilder<AuthnStatement>) getBuilderFactory().getBuilder(
109                 AuthnStatement.DEFAULT_ELEMENT_NAME);
110         authnContextBuilder = (SAMLObjectBuilder<AuthnContext>) getBuilderFactory().getBuilder(
111                 AuthnContext.DEFAULT_ELEMENT_NAME);
112         authnContextClassRefBuilder = (SAMLObjectBuilder<AuthnContextClassRef>) getBuilderFactory().getBuilder(
113                 AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
114         authnContextDeclRefBuilder = (SAMLObjectBuilder<AuthnContextDeclRef>) getBuilderFactory().getBuilder(
115                 AuthnContextDeclRef.DEFAULT_ELEMENT_NAME);
116         subjectLocalityBuilder = (SAMLObjectBuilder<SubjectLocality>) getBuilderFactory().getBuilder(
117                 SubjectLocality.DEFAULT_ELEMENT_NAME);
118         endpointBuilder = (SAMLObjectBuilder<Endpoint>) getBuilderFactory().getBuilder(
119                 AssertionConsumerService.DEFAULT_ELEMENT_NAME);
120     }
121
122     /** {@inheritDoc} */
123     public String getProfileId() {
124         return SSOConfiguration.PROFILE_ID;
125     }
126
127     /** {@inheritDoc} */
128     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
129         HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
130
131         LoginContext loginContext = (LoginContext) servletRequest.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
132         if (loginContext == null) {
133             log.debug("Incoming request does not contain a login context, processing as first leg of request");
134             performAuthentication(inTransport, outTransport);
135         } else {
136             log.debug("Incoming request contains a login context, processing as second leg of request");
137             completeAuthenticationRequest(inTransport, outTransport);
138         }
139     }
140
141     /**
142      * Creates a {@link Saml2LoginContext} an sends the request off to the AuthenticationManager to begin the process of
143      * authenticating the user.
144      * 
145      * @param inTransport inbound request transport
146      * @param outTransport outbound response transport
147      * 
148      * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
149      *             authentication manager
150      */
151     protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
152             throws ProfileException {
153         HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
154
155         try {
156             SSORequestContext requestContext = decodeRequest(inTransport, outTransport);
157
158             String relyingPartyId = requestContext.getInboundMessageIssuer();
159             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
160             ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(SSOConfiguration.PROFILE_ID);
161             if (ssoConfig == null) {
162                 log.error("SAML 2 SSO profile is not configured for relying party "
163                         + requestContext.getInboundMessageIssuer());
164                 throw new ProfileException("SAML 2 SSO profile is not configured for relying party "
165                         + requestContext.getInboundMessageIssuer());
166             }
167
168             log.debug("Creating login context and transferring control to authentication engine");
169             Saml2LoginContext loginContext = new Saml2LoginContext(relyingPartyId, requestContext.getRelayState(),
170                     requestContext.getInboundSAMLMessage());
171             loginContext.setAuthenticationEngineURL(authenticationManagerPath);
172             loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(servletRequest));
173             if (loginContext.getRequestedAuthenticationMethods().size() == 0) {
174                 loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
175             }
176
177             servletRequest.setAttribute(Saml2LoginContext.LOGIN_CONTEXT_KEY, loginContext);
178             RequestDispatcher dispatcher = servletRequest.getRequestDispatcher(authenticationManagerPath);
179             dispatcher.forward(servletRequest, ((HttpServletResponseAdapter) outTransport).getWrappedResponse());
180         } catch (MarshallingException e) {
181             log.error("Unable to marshall authentication request context");
182             throw new ProfileException("Unable to marshall authentication request context", e);
183         } catch (IOException ex) {
184             log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
185             throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
186         } catch (ServletException ex) {
187             log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
188             throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
189         }
190     }
191
192     /**
193      * Creates a response to the {@link AuthnRequest} and sends the user, with response in tow, back to the relying
194      * party after they've been authenticated.
195      * 
196      * @param inTransport inbound message transport
197      * @param outTransport outbound message transport
198      * 
199      * @throws ProfileException thrown if the response can not be created and sent back to the relying party
200      */
201     protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
202             throws ProfileException {
203         HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
204
205         Saml2LoginContext loginContext = (Saml2LoginContext) servletRequest
206                 .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
207         SSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
208
209         checkSamlVersion(requestContext);
210
211         Response samlResponse;
212         try {
213             if (loginContext.getAuthenticationFailure() != null) {
214                 log.error("User authentication failed with the following error: {}", loginContext
215                         .getAuthenticationFailure().toString());
216
217                 if (loginContext.getAuthenticationFailure() instanceof PassiveAuthenticationException) {
218                     requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.NO_PASSIVE_URI,
219                             null));
220                 } else {
221                     requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI,
222                             null));
223                 }
224                 throw new ProfileException("Authentication failure", loginContext.getAuthenticationFailure());
225             }
226
227             if (requestContext.getSubjectNameIdentifier() != null) {
228                 log
229                         .debug("Authentication request contained a subject with a name identifier, resolving principal from NameID");
230                 resolvePrincipal(requestContext);
231                 String requestedPrincipalName = requestContext.getPrincipalName();
232                 if (!DatatypeHelper.safeEquals(loginContext.getPrincipalName(), requestedPrincipalName)) {
233                     log
234                             .error(
235                                     "Authentication request identified principal {} but authentication mechanism identified principal {}",
236                                     requestedPrincipalName, loginContext.getPrincipalName());
237                     requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI,
238                             null));
239                     throw new ProfileException("User failed authentication");
240                 }
241             }
242
243             resolveAttributes(requestContext);
244
245             ArrayList<Statement> statements = new ArrayList<Statement>();
246             statements.add(buildAuthnStatement(requestContext));
247             if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
248                 AttributeStatement attributeStatement = buildAttributeStatement(requestContext);
249                 if (attributeStatement != null) {
250                     requestContext.setRequestedAttributes(requestContext.getAttributes().keySet());
251                     statements.add(attributeStatement);
252                 }
253             }
254
255             samlResponse = buildResponse(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:bearer", statements);
256         } catch (ProfileException e) {
257             samlResponse = buildErrorResponse(requestContext);
258         }
259
260         requestContext.setOutboundSAMLMessage(samlResponse);
261         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
262         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
263         encodeResponse(requestContext);
264         writeAuditLogEntry(requestContext);
265     }
266
267     /**
268      * Decodes an incoming request and stores the information in a created request context.
269      * 
270      * @param inTransport inbound transport
271      * @param outTransport outbound transport
272      * 
273      * @return request context with decoded information
274      * 
275      * @throws ProfileException thrown if the incoming message failed decoding
276      */
277     protected SSORequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
278             throws ProfileException {
279         log.debug("Decoding message with decoder binding {}", getInboundBinding());
280         SSORequestContext requestContext = new SSORequestContext();
281         requestContext.setCommunicationProfileId(getProfileId());
282         
283         requestContext.setMetadataProvider(getMetadataProvider());
284         requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
285
286         requestContext.setCommunicationProfileId(SSOConfiguration.PROFILE_ID);
287         requestContext.setInboundMessageTransport(inTransport);
288         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
289         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
290
291         requestContext.setOutboundMessageTransport(outTransport);
292         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
293
294         try {
295             SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
296             requestContext.setMessageDecoder(decoder);
297             decoder.decode(requestContext);
298             log.debug("Decoded request");
299
300             if (!(requestContext.getInboundMessage() instanceof AuthnRequest)) {
301                 log.error("Incomming message was not a AuthnRequest, it was a {}", requestContext.getInboundMessage()
302                         .getClass().getName());
303                 requestContext.setFailureStatus(buildStatus(StatusCode.REQUESTER_URI, null,
304                         "Invalid SAML AuthnRequest message."));
305                 throw new ProfileException("Invalid SAML AuthnRequest message.");
306             }
307
308             return requestContext;
309         } catch (MessageDecodingException e) {
310             log.error("Error decoding authentication request message", e);
311             throw new ProfileException("Error decoding authentication request message", e);
312         } catch (SecurityException e) {
313             log.error("Message did not meet security requirements", e);
314             throw new ProfileException("Message did not meet security requirements", e);
315         }
316     }
317
318     /**
319      * Creates an authentication request context from the current environmental information.
320      * 
321      * @param loginContext current login context
322      * @param in inbound transport
323      * @param out outbount transport
324      * 
325      * @return created authentication request context
326      * 
327      * @throws ProfileException thrown if there is a problem creating the context
328      */
329     protected SSORequestContext buildRequestContext(Saml2LoginContext loginContext, HTTPInTransport in,
330             HTTPOutTransport out) throws ProfileException {
331         SSORequestContext requestContext = new SSORequestContext();
332         requestContext.setCommunicationProfileId(getProfileId());
333
334         requestContext.setMessageDecoder(getMessageDecoders().get(getInboundBinding()));
335
336         requestContext.setLoginContext(loginContext);
337
338         requestContext.setInboundMessageTransport(in);
339         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
340
341         requestContext.setOutboundMessageTransport(out);
342         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
343
344         requestContext.setMetadataProvider(getMetadataProvider());
345
346         String relyingPartyId = loginContext.getRelyingPartyId();
347         requestContext.setPeerEntityId(relyingPartyId);
348         requestContext.setInboundMessageIssuer(relyingPartyId);
349
350         populateRequestContext(requestContext);
351
352         return requestContext;
353     }
354
355     /** {@inheritDoc} */
356     protected void populateRelyingPartyInformation(BaseSAMLProfileRequestContext requestContext)
357             throws ProfileException {
358         super.populateRelyingPartyInformation(requestContext);
359
360         EntityDescriptor relyingPartyMetadata = requestContext.getPeerEntityMetadata();
361         if (relyingPartyMetadata != null) {
362             requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
363             requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS));
364         }
365     }
366
367     /** {@inheritDoc} */
368     protected void populateAssertingPartyInformation(BaseSAMLProfileRequestContext requestContext)
369             throws ProfileException {
370         super.populateAssertingPartyInformation(requestContext);
371
372         EntityDescriptor localEntityDescriptor = requestContext.getLocalEntityMetadata();
373         if (localEntityDescriptor != null) {
374             requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
375             requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
376                     .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
377         }
378     }
379
380     /**
381      * Populates the request context with information from the inbound SAML message.
382      * 
383      * This method requires the the following request context properties to be populated: login context
384      * 
385      * This methods populates the following request context properties: inbound saml message, relay state, inbound saml
386      * message ID, subject name identifier
387      * 
388      * @param requestContext current request context
389      * 
390      * @throws ProfileException thrown if the inbound SAML message or subject identifier is null
391      */
392     protected void populateSAMLMessageInformation(BaseSAMLProfileRequestContext requestContext) throws ProfileException {
393         SSORequestContext ssoRequestContext = (SSORequestContext) requestContext;
394         try {
395             Saml2LoginContext loginContext = ssoRequestContext.getLoginContext();
396             requestContext.setRelayState(loginContext.getRelayState());
397
398             AuthnRequest authnRequest = loginContext.getAuthenticationRequest();
399             requestContext.setInboundMessage(authnRequest);
400             requestContext.setInboundSAMLMessage(loginContext.getAuthenticationRequest());
401             requestContext.setInboundSAMLMessageId(loginContext.getAuthenticationRequest().getID());
402
403             Subject authnSubject = authnRequest.getSubject();
404             if (authnSubject != null) {
405                 requestContext.setSubjectNameIdentifier(authnSubject.getNameID());
406             }
407         } catch (UnmarshallingException e) {
408             log.error("Unable to unmarshall authentication request context");
409             ssoRequestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
410                     "Error recovering request state"));
411             throw new ProfileException("Error recovering request state", e);
412         }
413     }
414
415     /**
416      * Creates an authentication statement for the current request.
417      * 
418      * @param requestContext current request context
419      * 
420      * @return constructed authentication statement
421      */
422     protected AuthnStatement buildAuthnStatement(SSORequestContext requestContext) {
423         Saml2LoginContext loginContext = requestContext.getLoginContext();
424
425         AuthnContext authnContext = buildAuthnContext(requestContext);
426
427         AuthnStatement statement = authnStatementBuilder.buildObject();
428         statement.setAuthnContext(authnContext);
429         statement.setAuthnInstant(loginContext.getAuthenticationInstant());
430
431         Session session = getUserSession(requestContext.getInboundMessageTransport());
432         if (session != null) {
433             statement.setSessionIndex(session.getSessionID());
434         }
435
436         if (loginContext.getAuthenticationDuration() > 0) {
437             statement.setSessionNotOnOrAfter(loginContext.getAuthenticationInstant().plus(
438                     loginContext.getAuthenticationDuration()));
439         }
440
441         statement.setSubjectLocality(buildSubjectLocality(requestContext));
442
443         return statement;
444     }
445
446     /**
447      * Creates an {@link AuthnContext} for a succesful authentication request.
448      * 
449      * @param requestContext current request
450      * 
451      * @return the built authn context
452      */
453     protected AuthnContext buildAuthnContext(SSORequestContext requestContext) {
454         AuthnContext authnContext = authnContextBuilder.buildObject();
455
456         Saml2LoginContext loginContext = requestContext.getLoginContext();
457         AuthnRequest authnRequest = requestContext.getInboundSAMLMessage();
458         RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
459         if (requestedAuthnContext != null) {
460             if (requestedAuthnContext.getAuthnContextClassRefs() != null) {
461                 for (AuthnContextClassRef classRef : requestedAuthnContext.getAuthnContextClassRefs()) {
462                     if (classRef.getAuthnContextClassRef().equals(loginContext.getAuthenticationMethod())) {
463                         AuthnContextClassRef ref = authnContextClassRefBuilder.buildObject();
464                         ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
465                         authnContext.setAuthnContextClassRef(ref);
466                     }
467                 }
468             } else if (requestedAuthnContext.getAuthnContextDeclRefs() != null) {
469                 for (AuthnContextDeclRef declRef : requestedAuthnContext.getAuthnContextDeclRefs()) {
470                     if (declRef.getAuthnContextDeclRef().equals(loginContext.getAuthenticationMethod())) {
471                         AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
472                         ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
473                         authnContext.setAuthnContextDeclRef(ref);
474                     }
475                 }
476             }
477         } else {
478             AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
479             ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
480             authnContext.setAuthnContextDeclRef(ref);
481         }
482
483         return authnContext;
484     }
485
486     /**
487      * Constructs the subject locality for the authentication statement.
488      * 
489      * @param requestContext curent request context
490      * 
491      * @return subject locality for the authentication statement
492      */
493     protected SubjectLocality buildSubjectLocality(SSORequestContext requestContext) {
494         HTTPInTransport transport = (HTTPInTransport) requestContext.getInboundMessageTransport();
495         SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
496         subjectLocality.setAddress(transport.getPeerAddress());
497
498         return subjectLocality;
499     }
500
501     /**
502      * Selects the appropriate endpoint for the relying party and stores it in the request context.
503      * 
504      * @param requestContext current request context
505      * 
506      * @return Endpoint selected from the information provided in the request context
507      */
508     protected Endpoint selectEndpoint(BaseSAMLProfileRequestContext requestContext) {
509         AuthnRequest authnRequest = ((SSORequestContext) requestContext).getInboundSAMLMessage();
510
511         AuthnResponseEndpointSelector endpointSelector = new AuthnResponseEndpointSelector();
512         endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
513         endpointSelector.setMetadataProvider(getMetadataProvider());
514         endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
515         endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
516         endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
517         endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
518
519         Endpoint endpoint = endpointSelector.selectEndpoint();
520         if (endpoint == null && authnRequest.getAssertionConsumerServiceURL() != null) {
521             endpoint = endpointBuilder.buildObject();
522             endpoint.setLocation(authnRequest.getAssertionConsumerServiceURL());
523             if (authnRequest.getProtocolBinding() != null) {
524                 endpoint.setBinding(authnRequest.getProtocolBinding());
525             } else {
526                 endpoint.setBinding(getSupportedOutboundBindings().get(0));
527             }
528             log.warn("No endpoint available for relying party {}. Generating endpoint with ACS url {} and binding {}",
529                     new Object[] { requestContext.getPeerEntityId(), endpoint.getLocation(), endpoint.getBinding() });
530         }
531
532         return endpoint;
533     }
534
535     /** Represents the internal state of a SAML 2.0 SSO Request while it's being processed by the IdP. */
536     protected class SSORequestContext extends BaseSAML2ProfileRequestContext<AuthnRequest, Response, SSOConfiguration> {
537
538         /** Current login context. */
539         private Saml2LoginContext loginContext;
540
541         /**
542          * Gets the current login context.
543          * 
544          * @return current login context
545          */
546         public Saml2LoginContext getLoginContext() {
547             return loginContext;
548         }
549
550         /**
551          * Sets the current login context.
552          * 
553          * @param context current login context
554          */
555         public void setLoginContext(Saml2LoginContext context) {
556             loginContext = context;
557         }
558     }
559 }