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