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