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