Add explicit option for support SessionNotOnOrAfter attribute in AuthnStatement;...
[java-idp.git] / src / main / java / edu / internet2 / middleware / shibboleth / idp / profile / saml2 / SSOProfileHandler.java
1 /*
2  * Copyright 2007 University Corporation for Advanced Internet Development, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package edu.internet2.middleware.shibboleth.idp.profile.saml2;
18
19 import java.io.IOException;
20 import java.util.ArrayList;
21
22 import javax.servlet.RequestDispatcher;
23 import javax.servlet.ServletException;
24 import javax.servlet.http.HttpServletRequest;
25
26 import org.joda.time.DateTime;
27 import org.joda.time.DateTimeZone;
28 import org.opensaml.common.SAMLObjectBuilder;
29 import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
30 import org.opensaml.common.xml.SAMLConstants;
31 import org.opensaml.saml2.binding.AuthnResponseEndpointSelector;
32 import org.opensaml.saml2.core.AttributeStatement;
33 import org.opensaml.saml2.core.AuthnContext;
34 import org.opensaml.saml2.core.AuthnContextClassRef;
35 import org.opensaml.saml2.core.AuthnContextDeclRef;
36 import org.opensaml.saml2.core.AuthnRequest;
37 import org.opensaml.saml2.core.AuthnStatement;
38 import org.opensaml.saml2.core.RequestedAuthnContext;
39 import org.opensaml.saml2.core.Response;
40 import org.opensaml.saml2.core.Statement;
41 import org.opensaml.saml2.core.StatusCode;
42 import org.opensaml.saml2.core.Subject;
43 import org.opensaml.saml2.core.SubjectLocality;
44 import org.opensaml.saml2.metadata.AssertionConsumerService;
45 import org.opensaml.saml2.metadata.Endpoint;
46 import org.opensaml.saml2.metadata.EntityDescriptor;
47 import org.opensaml.saml2.metadata.IDPSSODescriptor;
48 import org.opensaml.saml2.metadata.SPSSODescriptor;
49 import org.opensaml.ws.message.decoder.MessageDecodingException;
50 import org.opensaml.ws.transport.http.HTTPInTransport;
51 import org.opensaml.ws.transport.http.HTTPOutTransport;
52 import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
53 import org.opensaml.ws.transport.http.HttpServletResponseAdapter;
54 import org.opensaml.xml.io.MarshallingException;
55 import org.opensaml.xml.io.UnmarshallingException;
56 import org.opensaml.xml.security.SecurityException;
57 import org.opensaml.xml.util.DatatypeHelper;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
60
61 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
62 import edu.internet2.middleware.shibboleth.common.profile.provider.BaseSAMLProfileRequestContext;
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.SAMLMDRelyingPartyConfigurationManager;
66 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.SSOConfiguration;
67 import edu.internet2.middleware.shibboleth.common.util.HttpHelper;
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     /** Builder of Endpoint objects. */
95     private SAMLObjectBuilder<Endpoint> endpointBuilder;
96
97     /** URL of the authentication manager servlet. */
98     private String authenticationManagerPath;
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         endpointBuilder = (SAMLObjectBuilder<Endpoint>) getBuilderFactory().getBuilder(
122                 AssertionConsumerService.DEFAULT_ELEMENT_NAME);
123     }
124
125     /** {@inheritDoc} */
126     public String getProfileId() {
127         return SSOConfiguration.PROFILE_ID;
128     }
129
130     /** {@inheritDoc} */
131     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
132         HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
133
134         LoginContext loginContext = (LoginContext) servletRequest.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
135         if (loginContext == null) {
136             log.debug("Incoming request does not contain a login context, processing as first leg of request");
137             performAuthentication(inTransport, outTransport);
138         } else {
139             log.debug("Incoming request 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
158         try {
159             SSORequestContext requestContext = decodeRequest(inTransport, outTransport);
160
161             String relyingPartyId = requestContext.getInboundMessageIssuer();
162             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
163             ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(SSOConfiguration.PROFILE_ID);
164             if (ssoConfig == null) {
165                 log.error("SAML 2 SSO profile is not configured for relying party "
166                         + requestContext.getInboundMessageIssuer());
167                 throw new ProfileException("SAML 2 SSO profile is not configured for relying party "
168                         + requestContext.getInboundMessageIssuer());
169             }
170
171             log.debug("Creating login context and transferring control to authentication engine");
172             Saml2LoginContext loginContext = new Saml2LoginContext(relyingPartyId, requestContext.getRelayState(),
173                     requestContext.getInboundSAMLMessage());
174             loginContext.setAuthenticationEngineURL(authenticationManagerPath);
175             loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(servletRequest));
176             if (loginContext.getRequestedAuthenticationMethods().size() == 0
177                     && rpConfig.getDefaultAuthenticationMethod() != null) {
178                 loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
179             }
180
181             servletRequest.setAttribute(Saml2LoginContext.LOGIN_CONTEXT_KEY, loginContext);
182             RequestDispatcher dispatcher = servletRequest.getRequestDispatcher(authenticationManagerPath);
183             dispatcher.forward(servletRequest, ((HttpServletResponseAdapter) outTransport).getWrappedResponse());
184         } catch (MarshallingException e) {
185             log.error("Unable to marshall authentication request context");
186             throw new ProfileException("Unable to marshall authentication request context", e);
187         } catch (IOException ex) {
188             log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
189             throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
190         } catch (ServletException ex) {
191             log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
192             throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
193         }
194     }
195
196     /**
197      * Creates a response to the {@link AuthnRequest} and sends the user, with response in tow, back to the relying
198      * party after they've been authenticated.
199      * 
200      * @param inTransport inbound message transport
201      * @param outTransport outbound message transport
202      * 
203      * @throws ProfileException thrown if the response can not be created and sent back to the relying party
204      */
205     protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
206             throws ProfileException {
207         HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
208
209         Saml2LoginContext loginContext = (Saml2LoginContext) servletRequest
210                 .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
211         SSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
212
213         checkSamlVersion(requestContext);
214
215         Response samlResponse;
216         try {
217             if (loginContext.getAuthenticationFailure() != null) {
218                 log.error("User authentication failed with the following error: {}", loginContext
219                         .getAuthenticationFailure().toString());
220
221                 if (loginContext.getAuthenticationFailure() instanceof PassiveAuthenticationException) {
222                     requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.NO_PASSIVE_URI,
223                             null));
224                 } else {
225                     requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI,
226                             null));
227                 }
228                 throw new ProfileException("Authentication failure", loginContext.getAuthenticationFailure());
229             }
230
231             if (requestContext.getSubjectNameIdentifier() != null) {
232                 log
233                         .debug("Authentication request contained a subject with a name identifier, resolving principal from NameID");
234                 resolvePrincipal(requestContext);
235                 String requestedPrincipalName = requestContext.getPrincipalName();
236                 if (!DatatypeHelper.safeEquals(loginContext.getPrincipalName(), requestedPrincipalName)) {
237                     log
238                             .error(
239                                     "Authentication request identified principal {} but authentication mechanism identified principal {}",
240                                     requestedPrincipalName, loginContext.getPrincipalName());
241                     requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI,
242                             null));
243                     throw new ProfileException("User failed authentication");
244                 }
245             }
246
247             resolveAttributes(requestContext);
248
249             ArrayList<Statement> statements = new ArrayList<Statement>();
250             statements.add(buildAuthnStatement(requestContext));
251             if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
252                 AttributeStatement attributeStatement = buildAttributeStatement(requestContext);
253                 if (attributeStatement != null) {
254                     requestContext.setReleasedAttributes(requestContext.getAttributes().keySet());
255                     statements.add(attributeStatement);
256                 }
257             }
258
259             samlResponse = buildResponse(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:bearer", statements);
260         } catch (ProfileException e) {
261             samlResponse = buildErrorResponse(requestContext);
262         }
263
264         requestContext.setOutboundSAMLMessage(samlResponse);
265         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
266         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
267         encodeResponse(requestContext);
268         writeAuditLogEntry(requestContext);
269     }
270
271     /**
272      * Decodes an incoming request and stores the information in a created request context.
273      * 
274      * @param inTransport inbound transport
275      * @param outTransport outbound transport
276      * 
277      * @return request context with decoded information
278      * 
279      * @throws ProfileException thrown if the incoming message failed decoding
280      */
281     protected SSORequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
282             throws ProfileException {
283         log.debug("Decoding message with decoder binding {}", getInboundBinding());
284         SSORequestContext requestContext = new SSORequestContext();
285         requestContext.setCommunicationProfileId(getProfileId());
286
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         requestContext.setCommunicationProfileId(getProfileId());
337
338         requestContext.setMessageDecoder(getMessageDecoders().get(getInboundBinding()));
339
340         requestContext.setLoginContext(loginContext);
341
342         requestContext.setInboundMessageTransport(in);
343         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
344
345         requestContext.setOutboundMessageTransport(out);
346         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
347
348         requestContext.setMetadataProvider(getMetadataProvider());
349
350         String relyingPartyId = loginContext.getRelyingPartyId();
351         requestContext.setPeerEntityId(relyingPartyId);
352         requestContext.setInboundMessageIssuer(relyingPartyId);
353
354         populateRequestContext(requestContext);
355
356         return requestContext;
357     }
358
359     /** {@inheritDoc} */
360     protected void populateRelyingPartyInformation(BaseSAMLProfileRequestContext requestContext)
361             throws ProfileException {
362         super.populateRelyingPartyInformation(requestContext);
363
364         EntityDescriptor relyingPartyMetadata = requestContext.getPeerEntityMetadata();
365         if (relyingPartyMetadata != null) {
366             requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
367             requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS));
368         }
369     }
370
371     /** {@inheritDoc} */
372     protected void populateAssertingPartyInformation(BaseSAMLProfileRequestContext requestContext)
373             throws ProfileException {
374         super.populateAssertingPartyInformation(requestContext);
375
376         EntityDescriptor localEntityDescriptor = requestContext.getLocalEntityMetadata();
377         if (localEntityDescriptor != null) {
378             requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
379             requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
380                     .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
381         }
382     }
383
384     /**
385      * Populates the request context with information from the inbound SAML message.
386      * 
387      * This method requires the the following request context properties to be populated: login context
388      * 
389      * This methods populates the following request context properties: inbound saml message, relay state, inbound saml
390      * message ID, subject name identifier
391      * 
392      * @param requestContext current request context
393      * 
394      * @throws ProfileException thrown if the inbound SAML message or subject identifier is null
395      */
396     protected void populateSAMLMessageInformation(BaseSAMLProfileRequestContext requestContext) throws ProfileException {
397         SSORequestContext ssoRequestContext = (SSORequestContext) requestContext;
398         try {
399             Saml2LoginContext loginContext = ssoRequestContext.getLoginContext();
400             requestContext.setRelayState(loginContext.getRelayState());
401
402             AuthnRequest authnRequest = loginContext.getAuthenticationRequest();
403             requestContext.setInboundMessage(authnRequest);
404             requestContext.setInboundSAMLMessage(loginContext.getAuthenticationRequest());
405             requestContext.setInboundSAMLMessageId(loginContext.getAuthenticationRequest().getID());
406
407             Subject authnSubject = authnRequest.getSubject();
408             if (authnSubject != null) {
409                 requestContext.setSubjectNameIdentifier(authnSubject.getNameID());
410             }
411         } catch (UnmarshallingException e) {
412             log.error("Unable to unmarshall authentication request context");
413             ssoRequestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
414                     "Error recovering request state"));
415             throw new ProfileException("Error recovering request state", e);
416         }
417     }
418
419     /**
420      * Creates an authentication statement for the current request.
421      * 
422      * @param requestContext current request context
423      * 
424      * @return constructed authentication statement
425      */
426     protected AuthnStatement buildAuthnStatement(SSORequestContext requestContext) {
427         Saml2LoginContext loginContext = requestContext.getLoginContext();
428
429         AuthnContext authnContext = buildAuthnContext(requestContext);
430
431         AuthnStatement statement = authnStatementBuilder.buildObject();
432         statement.setAuthnContext(authnContext);
433         statement.setAuthnInstant(loginContext.getAuthenticationInstant());
434
435         Session session = getUserSession(requestContext.getInboundMessageTransport());
436         if (session != null) {
437             statement.setSessionIndex(session.getSessionID());
438         }
439
440         long maxSPSessionLifetime = requestContext.getProfileConfiguration().getMaximumSPSessionLifetime();
441         if (maxSPSessionLifetime > 0) {
442             DateTime lifetime = new DateTime(DateTimeZone.UTC).plus(maxSPSessionLifetime);
443             log.debug("Explicitly setting SP session expiration time to {}", lifetime.toString());
444             statement.setSessionNotOnOrAfter(lifetime);
445         }
446
447         statement.setSubjectLocality(buildSubjectLocality(requestContext));
448
449         return statement;
450     }
451
452     /**
453      * Creates an {@link AuthnContext} for a succesful authentication request.
454      * 
455      * @param requestContext current request
456      * 
457      * @return the built authn context
458      */
459     protected AuthnContext buildAuthnContext(SSORequestContext requestContext) {
460         AuthnContext authnContext = authnContextBuilder.buildObject();
461
462         Saml2LoginContext loginContext = requestContext.getLoginContext();
463         AuthnRequest authnRequest = requestContext.getInboundSAMLMessage();
464         RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
465         if (requestedAuthnContext != null) {
466             if (requestedAuthnContext.getAuthnContextClassRefs() != null) {
467                 for (AuthnContextClassRef classRef : requestedAuthnContext.getAuthnContextClassRefs()) {
468                     if (classRef.getAuthnContextClassRef().equals(loginContext.getAuthenticationMethod())) {
469                         AuthnContextClassRef ref = authnContextClassRefBuilder.buildObject();
470                         ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
471                         authnContext.setAuthnContextClassRef(ref);
472                     }
473                 }
474             } else if (requestedAuthnContext.getAuthnContextDeclRefs() != null) {
475                 for (AuthnContextDeclRef declRef : requestedAuthnContext.getAuthnContextDeclRefs()) {
476                     if (declRef.getAuthnContextDeclRef().equals(loginContext.getAuthenticationMethod())) {
477                         AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
478                         ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
479                         authnContext.setAuthnContextDeclRef(ref);
480                     }
481                 }
482             }
483         } else {
484             AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
485             ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
486             authnContext.setAuthnContextDeclRef(ref);
487         }
488
489         return authnContext;
490     }
491
492     /**
493      * Constructs the subject locality for the authentication statement.
494      * 
495      * @param requestContext curent request context
496      * 
497      * @return subject locality for the authentication statement
498      */
499     protected SubjectLocality buildSubjectLocality(SSORequestContext requestContext) {
500         HTTPInTransport transport = (HTTPInTransport) requestContext.getInboundMessageTransport();
501         SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
502         subjectLocality.setAddress(transport.getPeerAddress());
503
504         return subjectLocality;
505     }
506
507     /**
508      * Selects the appropriate endpoint for the relying party and stores it in the request context.
509      * 
510      * @param requestContext current request context
511      * 
512      * @return Endpoint selected from the information provided in the request context
513      */
514     protected Endpoint selectEndpoint(BaseSAMLProfileRequestContext requestContext) {
515         AuthnRequest authnRequest = ((SSORequestContext) requestContext).getInboundSAMLMessage();
516
517         Endpoint endpoint = null;
518         if (requestContext.getRelyingPartyConfiguration().getRelyingPartyId() == SAMLMDRelyingPartyConfigurationManager.ANONYMOUS_RP_NAME) {
519             if (authnRequest.getAssertionConsumerServiceURL() != null) {
520                 endpoint = endpointBuilder.buildObject();
521                 endpoint.setLocation(authnRequest.getAssertionConsumerServiceURL());
522                 if (authnRequest.getProtocolBinding() != null) {
523                     endpoint.setBinding(authnRequest.getProtocolBinding());
524                 } else {
525                     endpoint.setBinding(getSupportedOutboundBindings().get(0));
526                 }
527                 log.warn("Generating endpoint for anonymous relying party. ACS url {} and binding {}", new Object[] {
528                         requestContext.getInboundMessageIssuer(), endpoint.getLocation(), endpoint.getBinding(), });
529             } else {
530                 log.warn("Unable to generate endpoint for anonymous party.  No ACS url provided.");
531             }
532         } else {
533             AuthnResponseEndpointSelector endpointSelector = new AuthnResponseEndpointSelector();
534             endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
535             endpointSelector.setMetadataProvider(getMetadataProvider());
536             endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
537             endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
538             endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
539             endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
540             endpoint = endpointSelector.selectEndpoint();
541         }
542
543         return endpoint;
544     }
545
546     /** Represents the internal state of a SAML 2.0 SSO Request while it's being processed by the IdP. */
547     protected class SSORequestContext extends BaseSAML2ProfileRequestContext<AuthnRequest, Response, SSOConfiguration> {
548
549         /** Current login context. */
550         private Saml2LoginContext loginContext;
551
552         /**
553          * Gets the current login context.
554          * 
555          * @return current login context
556          */
557         public Saml2LoginContext getLoginContext() {
558             return loginContext;
559         }
560
561         /**
562          * Sets the current login context.
563          * 
564          * @param context current login context
565          */
566         public void setLoginContext(Saml2LoginContext context) {
567             loginContext = context;
568         }
569     }
570 }