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