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