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