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