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