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