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