Fix logging message, addresses SIDP-90
[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 import javax.servlet.http.HttpSession;
26
27 import org.opensaml.common.SAMLObjectBuilder;
28 import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
29 import org.opensaml.common.xml.SAMLConstants;
30 import org.opensaml.saml2.binding.AuthnResponseEndpointSelector;
31 import org.opensaml.saml2.core.AttributeStatement;
32 import org.opensaml.saml2.core.AuthnContext;
33 import org.opensaml.saml2.core.AuthnContextClassRef;
34 import org.opensaml.saml2.core.AuthnContextDeclRef;
35 import org.opensaml.saml2.core.AuthnRequest;
36 import org.opensaml.saml2.core.AuthnStatement;
37 import org.opensaml.saml2.core.RequestedAuthnContext;
38 import org.opensaml.saml2.core.Response;
39 import org.opensaml.saml2.core.Statement;
40 import org.opensaml.saml2.core.StatusCode;
41 import org.opensaml.saml2.core.Subject;
42 import org.opensaml.saml2.core.SubjectLocality;
43 import org.opensaml.saml2.metadata.AssertionConsumerService;
44 import org.opensaml.saml2.metadata.Endpoint;
45 import org.opensaml.saml2.metadata.EntityDescriptor;
46 import org.opensaml.saml2.metadata.IDPSSODescriptor;
47 import org.opensaml.saml2.metadata.SPSSODescriptor;
48 import org.opensaml.saml2.metadata.provider.MetadataProvider;
49 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
50 import org.opensaml.ws.message.decoder.MessageDecodingException;
51 import org.opensaml.ws.transport.http.HTTPInTransport;
52 import org.opensaml.ws.transport.http.HTTPOutTransport;
53 import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
54 import org.opensaml.ws.transport.http.HttpServletResponseAdapter;
55 import org.opensaml.xml.io.MarshallingException;
56 import org.opensaml.xml.io.UnmarshallingException;
57 import org.opensaml.xml.security.SecurityException;
58 import org.opensaml.xml.util.DatatypeHelper;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61
62 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
63 import edu.internet2.middleware.shibboleth.common.relyingparty.ProfileConfiguration;
64 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
65 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.SSOConfiguration;
66 import edu.internet2.middleware.shibboleth.common.util.HttpHelper;
67 import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
68 import edu.internet2.middleware.shibboleth.idp.authn.Saml2LoginContext;
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     /** URL of the authentication manager servlet. */
92     private String authenticationManagerPath;
93
94     /** URI of request decoder. */
95     private String decodingBinding;
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     }
119
120     /** {@inheritDoc} */
121     public String getProfileId() {
122         return "urn:mace:shibboleth:2.0:idp:profiles:saml2:request:sso";
123     }
124
125     /** {@inheritDoc} */
126     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
127         HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
128         HttpSession httpSession = servletRequest.getSession(true);
129         LoginContext loginContext = (LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
130
131         if (loginContext == null) {
132             log.debug("User session does not contain a login context, processing as first leg of request");
133             performAuthentication(inTransport, outTransport);
134         } else if (!loginContext.isPrincipalAuthenticated()) {
135             log.debug("User session contained a login context but user was not authenticated, processing as first leg of request");
136             performAuthentication(inTransport, outTransport);
137         } else {
138             log.debug("User session contains a login context, processing as second leg of request");
139             completeAuthenticationRequest(inTransport, outTransport);
140         }
141     }
142
143     /**
144      * Creates a {@link Saml2LoginContext} an sends the request off to the AuthenticationManager to begin the process of
145      * authenticating the user.
146      * 
147      * @param inTransport inbound request transport
148      * @param outTransport outbound response transport
149      * 
150      * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
151      *             authentication manager
152      */
153     protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
154             throws ProfileException {
155         HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
156         HttpSession httpSession = servletRequest.getSession();
157
158         try {
159             SSORequestContext requestContext = decodeRequest(inTransport, outTransport);
160
161             String relyingPartyId = requestContext.getInboundMessageIssuer();
162             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
163             ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(SSOConfiguration.PROFILE_ID);
164             if (ssoConfig == null) {
165                 log.error("SAML 2 SSO profile is not configured for relying party "
166                         + requestContext.getInboundMessageIssuer());
167                 throw new ProfileException("SAML 2 SSO profile is not configured for relying party "
168                         + requestContext.getInboundMessageIssuer());
169             }
170
171             log.debug("Creating login context and transferring control to authentication engine");
172             Saml2LoginContext loginContext = new Saml2LoginContext(relyingPartyId, requestContext.getRelayState(),
173                     requestContext.getInboundSAMLMessage());
174             loginContext.setAuthenticationEngineURL(authenticationManagerPath);
175             loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(servletRequest));
176             if (loginContext.getRequestedAuthenticationMethods().size() == 0) {
177                 loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
178             }
179
180             httpSession.setAttribute(Saml2LoginContext.LOGIN_CONTEXT_KEY, loginContext);
181             RequestDispatcher dispatcher = servletRequest.getRequestDispatcher(authenticationManagerPath);
182             dispatcher.forward(servletRequest, ((HttpServletResponseAdapter) outTransport).getWrappedResponse());
183         } catch (MarshallingException e) {
184             httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
185             log.error("Unable to marshall authentication request context");
186             throw new ProfileException("Unable to marshall authentication request context", e);
187         } catch (IOException ex) {
188             httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
189             log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
190             throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
191         } catch (ServletException ex) {
192             httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
193             log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
194             throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
195         }
196     }
197
198     /**
199      * Creates a response to the {@link AuthnRequest} and sends the user, with response in tow, back to the relying
200      * party after they've been authenticated.
201      * 
202      * @param inTransport inbound message transport
203      * @param outTransport outbound message transport
204      * 
205      * @throws ProfileException thrown if the response can not be created and sent back to the relying party
206      */
207     protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
208             throws ProfileException {
209         HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
210         HttpSession httpSession = servletRequest.getSession();
211
212         Saml2LoginContext loginContext = (Saml2LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
213         httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
214
215         SSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
216
217         checkSamlVersion(requestContext);
218
219         Response samlResponse;
220         try {
221             if (loginContext.getPrincipalName() == null) {
222                 log.error("User's login context did not contain a principal, user considered unauthenticiated.");
223                 requestContext
224                         .setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI, null));
225                 throw new ProfileException("User failed authentication");
226             }
227
228             if (requestContext.getSubjectNameIdentifier() != null) {
229                 log.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.error("Authentication request identified principal {} but authentication mechanism identified principal {}",
234                                     requestedPrincipalName, loginContext.getPrincipalName());
235                     requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI,
236                             null));
237                     throw new ProfileException("User failed authentication");
238                 }
239             }
240
241             resolveAttributes(requestContext);
242
243             ArrayList<Statement> statements = new ArrayList<Statement>();
244             statements.add(buildAuthnStatement(requestContext));
245             if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
246                 AttributeStatement attributeStatement = buildAttributeStatement(requestContext);
247                 if (attributeStatement != null) {
248                     requestContext.setRequestedAttributes(requestContext.getPrincipalAttributes().keySet());
249                     statements.add(attributeStatement);
250                 }
251             }
252
253             samlResponse = buildResponse(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:bearer", statements);
254         } catch (ProfileException e) {
255             samlResponse = buildErrorResponse(requestContext);
256         }
257
258         requestContext.setOutboundSAMLMessage(samlResponse);
259         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
260         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
261         encodeResponse(requestContext);
262         writeAuditLogEntry(requestContext);
263     }
264
265     /**
266      * Decodes an incoming request and stores the information in a created request context.
267      * 
268      * @param inTransport inbound transport
269      * @param outTransport outbound transport
270      * 
271      * @return request context with decoded information
272      * 
273      * @throws ProfileException thrown if the incomming message failed decoding
274      */
275     protected SSORequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
276             throws ProfileException {
277         log.debug("Decoding message with decoder binding {}", getInboundBinding());
278         SSORequestContext requestContext = new SSORequestContext();
279         requestContext.setMetadataProvider(getMetadataProvider());
280         requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
281
282         requestContext.setCommunicationProfileId(SSOConfiguration.PROFILE_ID);
283         requestContext.setInboundMessageTransport(inTransport);
284         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
285         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
286
287         requestContext.setOutboundMessageTransport(outTransport);
288         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
289
290         try {
291             SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
292             requestContext.setMessageDecoder(decoder);
293             decoder.decode(requestContext);
294             return requestContext;
295         } catch (MessageDecodingException e) {
296             log.error("Error decoding authentication request message", e);
297             throw new ProfileException("Error decoding authentication request message", e);
298         } catch (SecurityException e) {
299             log.error("Message did not meet security requirements", e);
300             throw new ProfileException("Message did not meet security requirements", e);
301         }
302     }
303
304     /**
305      * Creates an authentication request context from the current environmental information.
306      * 
307      * @param loginContext current login context
308      * @param in inbound transport
309      * @param out outbount transport
310      * 
311      * @return created authentication request context
312      * 
313      * @throws ProfileException thrown if there is a problem creating the context
314      */
315     protected SSORequestContext buildRequestContext(Saml2LoginContext loginContext, HTTPInTransport in,
316             HTTPOutTransport out) throws ProfileException {
317         SSORequestContext requestContext = new SSORequestContext();
318
319         requestContext.setMessageDecoder(getMessageDecoders().get(getInboundBinding()));
320
321         requestContext.setLoginContext(loginContext);
322         requestContext.setPrincipalName(loginContext.getPrincipalName());
323         requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
324         requestContext.setUserSession(getUserSession(in));
325         requestContext.setRelayState(loginContext.getRelayState());
326
327         requestContext.setInboundMessageTransport(in);
328         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
329
330         try {
331             AuthnRequest authnRequest = loginContext.getAuthenticationRequest();
332             requestContext.setInboundMessage(authnRequest);
333             requestContext.setInboundSAMLMessage(loginContext.getAuthenticationRequest());
334             requestContext.setInboundSAMLMessageId(loginContext.getAuthenticationRequest().getID());
335
336             Subject authnSubject = authnRequest.getSubject();
337             if (authnSubject != null) {
338                 requestContext.setSubjectNameIdentifier(authnSubject.getNameID());
339             }
340         } catch (UnmarshallingException e) {
341             log.error("Unable to unmarshall authentication request context");
342             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
343                     "Error recovering request state"));
344             throw new ProfileException("Error recovering request state", e);
345         }
346
347         requestContext.setOutboundMessageTransport(out);
348         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
349
350         MetadataProvider metadataProvider = getMetadataProvider();
351         requestContext.setMetadataProvider(metadataProvider);
352
353         String relyingPartyId = loginContext.getRelyingPartyId();
354         requestContext.setInboundMessageIssuer(relyingPartyId);
355         try {
356             EntityDescriptor relyingPartyMetadata = metadataProvider.getEntityDescriptor(relyingPartyId);
357             if (relyingPartyMetadata != null) {
358                 requestContext.setPeerEntityMetadata(relyingPartyMetadata);
359                 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
360                 requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata
361                         .getSPSSODescriptor(SAMLConstants.SAML20P_NS));
362             }
363         } catch (MetadataProviderException e) {
364             log.error("Unable to locate metadata for relying party");
365             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
366                     "Error locating relying party metadata"));
367             throw new ProfileException("Error locating relying party metadata");
368         }
369
370         RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
371         if (rpConfig == null) {
372             log.error("Unable to retrieve relying party configuration data for entity with ID {}", relyingPartyId);
373             throw new ProfileException("Unable to retrieve relying party configuration data for entity with ID "
374                     + relyingPartyId);
375         }
376         requestContext.setRelyingPartyConfiguration(rpConfig);
377
378         SSOConfiguration profileConfig = (SSOConfiguration) rpConfig
379                 .getProfileConfiguration(SSOConfiguration.PROFILE_ID);
380         requestContext.setProfileConfiguration(profileConfig);
381         requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
382         if (profileConfig.getSigningCredential() != null) {
383             requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
384         } else if (rpConfig.getDefaultSigningCredential() != null) {
385             requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
386         }
387         requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
388
389         String assertingPartyId = rpConfig.getProviderId();
390         requestContext.setLocalEntityId(assertingPartyId);
391
392         try {
393             EntityDescriptor localEntityDescriptor = metadataProvider.getEntityDescriptor(assertingPartyId);
394             if (localEntityDescriptor != null) {
395                 requestContext.setLocalEntityMetadata(localEntityDescriptor);
396                 requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
397                 requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
398                         .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
399             }
400         } catch (MetadataProviderException e) {
401             log.error("Unable to locate metadata for asserting party");
402             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
403                     "Error locating asserting party metadata"));
404             throw new ProfileException("Error locating asserting party metadata");
405         }
406
407         return requestContext;
408     }
409
410     /**
411      * Creates an authentication statement for the current request.
412      * 
413      * @param requestContext current request context
414      * 
415      * @return constructed authentication statement
416      */
417     protected AuthnStatement buildAuthnStatement(SSORequestContext requestContext) {
418         Saml2LoginContext loginContext = requestContext.getLoginContext();
419
420         AuthnContext authnContext = buildAuthnContext(requestContext);
421
422         AuthnStatement statement = authnStatementBuilder.buildObject();
423         statement.setAuthnContext(authnContext);
424         statement.setAuthnInstant(loginContext.getAuthenticationInstant());
425
426         // TODO
427         statement.setSessionIndex(null);
428
429         if (loginContext.getAuthenticationDuration() > 0) {
430             statement.setSessionNotOnOrAfter(loginContext.getAuthenticationInstant().plus(
431                     loginContext.getAuthenticationDuration()));
432         }
433
434         statement.setSubjectLocality(buildSubjectLocality(requestContext));
435
436         return statement;
437     }
438
439     /**
440      * Creates an {@link AuthnContext} for a succesful authentication request.
441      * 
442      * @param requestContext current request
443      * 
444      * @return the built authn context
445      */
446     protected AuthnContext buildAuthnContext(SSORequestContext requestContext) {
447         AuthnContext authnContext = authnContextBuilder.buildObject();
448
449         Saml2LoginContext loginContext = requestContext.getLoginContext();
450         AuthnRequest authnRequest = requestContext.getInboundSAMLMessage();
451         RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
452         if (requestedAuthnContext != null) {
453             if (requestedAuthnContext.getAuthnContextClassRefs() != null) {
454                 for (AuthnContextClassRef classRef : requestedAuthnContext.getAuthnContextClassRefs()) {
455                     if (classRef.getAuthnContextClassRef().equals(loginContext.getAuthenticationMethod())) {
456                         AuthnContextClassRef ref = authnContextClassRefBuilder.buildObject();
457                         ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
458                         authnContext.setAuthnContextClassRef(ref);
459                     }
460                 }
461             } else if (requestedAuthnContext.getAuthnContextDeclRefs() != null) {
462                 for (AuthnContextDeclRef declRef : requestedAuthnContext.getAuthnContextDeclRefs()) {
463                     if (declRef.getAuthnContextDeclRef().equals(loginContext.getAuthenticationMethod())) {
464                         AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
465                         ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
466                         authnContext.setAuthnContextDeclRef(ref);
467                     }
468                 }
469             }
470         } else {
471             AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
472             ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
473             authnContext.setAuthnContextDeclRef(ref);
474         }
475
476         return authnContext;
477     }
478
479     /**
480      * Constructs the subject locality for the authentication statement.
481      * 
482      * @param requestContext curent request context
483      * 
484      * @return subject locality for the authentication statement
485      */
486     protected SubjectLocality buildSubjectLocality(SSORequestContext requestContext) {
487         HTTPInTransport transport = (HTTPInTransport) requestContext.getInboundMessageTransport();
488         SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
489         subjectLocality.setAddress(transport.getPeerAddress());
490         subjectLocality.setDNSName(transport.getPeerDomainName());
491
492         return subjectLocality;
493     }
494
495     /**
496      * Selects the appropriate endpoint for the relying party and stores it in the request context.
497      * 
498      * @param requestContext current request context
499      * 
500      * @return Endpoint selected from the information provided in the request context
501      */
502     protected Endpoint selectEndpoint(SSORequestContext requestContext) {
503         AuthnResponseEndpointSelector endpointSelector = new AuthnResponseEndpointSelector();
504         endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
505         endpointSelector.setMetadataProvider(getMetadataProvider());
506         endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
507         endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
508         endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
509         endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
510         return endpointSelector.selectEndpoint();
511     }
512
513     /** Represents the internal state of a SAML 2.0 SSO Request while it's being processed by the IdP. */
514     protected class SSORequestContext extends BaseSAML2ProfileRequestContext<AuthnRequest, Response, SSOConfiguration> {
515
516         /** Current login context. */
517         private Saml2LoginContext loginContext;
518
519         /**
520          * Gets the current login context.
521          * 
522          * @return current login context
523          */
524         public Saml2LoginContext getLoginContext() {
525             return loginContext;
526         }
527
528         /**
529          * Sets the current login context.
530          * 
531          * @param context current login context
532          */
533         public void setLoginContext(Saml2LoginContext context) {
534             loginContext = context;
535         }
536     }
537 }