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