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