Check the inbound SAML message context slot, not the inbound message slot.
[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 import edu.internet2.middleware.shibboleth.idp.util.HttpServletHelper;
78
79 /** SAML 2.0 SSO request profile handler. */
80 public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
81
82     /** Class logger. */
83     private final Logger log = LoggerFactory.getLogger(SSOProfileHandler.class);
84
85     /** Builder of AuthnStatement objects. */
86     private SAMLObjectBuilder<AuthnStatement> authnStatementBuilder;
87
88     /** Builder of AuthnContext objects. */
89     private SAMLObjectBuilder<AuthnContext> authnContextBuilder;
90
91     /** Builder of AuthnContextClassRef objects. */
92     private SAMLObjectBuilder<AuthnContextClassRef> authnContextClassRefBuilder;
93
94     /** Builder of AuthnContextDeclRef objects. */
95     private SAMLObjectBuilder<AuthnContextDeclRef> authnContextDeclRefBuilder;
96
97     /** Builder of SubjectLocality objects. */
98     private SAMLObjectBuilder<SubjectLocality> subjectLocalityBuilder;
99
100     /** Builder of Endpoint objects. */
101     private SAMLObjectBuilder<Endpoint> endpointBuilder;
102
103     /** URL of the authentication manager Servlet. */
104     private String authenticationManagerPath;
105
106     /**
107      * Constructor.
108      * 
109      * @param authnManagerPath path to the authentication manager Servlet
110      */
111     @SuppressWarnings("unchecked")
112     public SSOProfileHandler(String authnManagerPath) {
113         super();
114
115         authenticationManagerPath = authnManagerPath;
116
117         authnStatementBuilder = (SAMLObjectBuilder<AuthnStatement>) getBuilderFactory().getBuilder(
118                 AuthnStatement.DEFAULT_ELEMENT_NAME);
119         authnContextBuilder = (SAMLObjectBuilder<AuthnContext>) getBuilderFactory().getBuilder(
120                 AuthnContext.DEFAULT_ELEMENT_NAME);
121         authnContextClassRefBuilder = (SAMLObjectBuilder<AuthnContextClassRef>) getBuilderFactory().getBuilder(
122                 AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
123         authnContextDeclRefBuilder = (SAMLObjectBuilder<AuthnContextDeclRef>) getBuilderFactory().getBuilder(
124                 AuthnContextDeclRef.DEFAULT_ELEMENT_NAME);
125         subjectLocalityBuilder = (SAMLObjectBuilder<SubjectLocality>) getBuilderFactory().getBuilder(
126                 SubjectLocality.DEFAULT_ELEMENT_NAME);
127         endpointBuilder = (SAMLObjectBuilder<Endpoint>) getBuilderFactory().getBuilder(
128                 AssertionConsumerService.DEFAULT_ELEMENT_NAME);
129     }
130
131     /** {@inheritDoc} */
132     public String getProfileId() {
133         return SSOConfiguration.PROFILE_ID;
134     }
135
136     /** {@inheritDoc} */
137     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
138         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
139
140         LoginContext loginContext = HttpServletHelper.getLoginContext(httpRequest);
141         if (loginContext == null) {
142             log.debug("Incoming request does not contain a login context, processing as first leg of request");
143             performAuthentication(inTransport, outTransport);
144         } else {
145             log.debug("Incoming request contains a login context, processing as second leg of request");
146             completeAuthenticationRequest(inTransport, outTransport);
147         }
148     }
149
150     /**
151      * Creates a {@link Saml2LoginContext} an sends the request off to the AuthenticationManager to begin the process of
152      * authenticating the user.
153      * 
154      * @param inTransport inbound request transport
155      * @param outTransport outbound response transport
156      * 
157      * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
158      *             authentication manager
159      */
160     protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
161             throws ProfileException {
162         HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
163         SSORequestContext requestContext = new SSORequestContext();
164
165         try {
166             decodeRequest(requestContext, inTransport, outTransport);
167
168             String relyingPartyId = requestContext.getInboundMessageIssuer();
169             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
170             ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(SSOConfiguration.PROFILE_ID);
171             if (ssoConfig == null) {
172                 String msg = MessageFormatter.format("SAML 2 SSO profile is not configured for relying party '{}'", requestContext.getInboundMessageIssuer());
173                 log.warn(msg);
174                 throw new ProfileException(msg);
175             }
176
177             log.debug("Creating login context and transferring control to authentication engine");
178             Saml2LoginContext loginContext = new Saml2LoginContext(relyingPartyId, requestContext.getRelayState(),
179                     requestContext.getInboundSAMLMessage());
180             loginContext.setAuthenticationEngineURL(authenticationManagerPath);
181             loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(servletRequest));
182             loginContext.setDefaultAuthenticationMethod(rpConfig.getDefaultAuthenticationMethod());
183             
184             HttpServletHelper.bindLoginContext(loginContext, servletRequest);
185             RequestDispatcher dispatcher = servletRequest.getRequestDispatcher(authenticationManagerPath);
186             dispatcher.forward(servletRequest, ((HttpServletResponseAdapter) outTransport).getWrappedResponse());
187         } catch (MarshallingException e) {
188             log.error("Unable to marshall authentication request context");
189             throw new ProfileException("Unable to marshall authentication request context", e);
190         } catch (IOException ex) {
191             log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
192             throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
193         } catch (ServletException ex) {
194             log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
195             throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
196         }
197     }
198
199     /**
200      * Creates a response to the {@link AuthnRequest} and sends the user, with response in tow, back to the relying
201      * party after they've been authenticated.
202      * 
203      * @param inTransport inbound message transport
204      * @param outTransport outbound message transport
205      * 
206      * @throws ProfileException thrown if the response can not be created and sent back to the relying party
207      */
208     protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
209             throws ProfileException {
210         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
211         Saml2LoginContext loginContext = (Saml2LoginContext) HttpServletHelper.getLoginContext(httpRequest);
212         
213         SSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
214
215         checkSamlVersion(requestContext);
216
217         Response samlResponse;
218         try {
219             if (loginContext.getAuthenticationFailure() != null) {
220                 if (loginContext.getAuthenticationFailure() instanceof PassiveAuthenticationException) {
221                     requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.NO_PASSIVE_URI,
222                             null));
223                 } else {
224                     requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI,
225                             null));
226                 }
227                 throw new ProfileException("Authentication failure", loginContext.getAuthenticationFailure());
228             }
229
230             if (requestContext.getSubjectNameIdentifier() != null) {
231                 log
232                         .debug("Authentication request contained a subject with a name identifier, resolving principal from NameID");
233                 resolvePrincipal(requestContext);
234                 String requestedPrincipalName = requestContext.getPrincipalName();
235                 if (!DatatypeHelper.safeEquals(loginContext.getPrincipalName(), requestedPrincipalName)) {
236                     log
237                             .warn(
238                                     "Authentication request identified principal {} but authentication mechanism identified principal {}",
239                                     requestedPrincipalName, loginContext.getPrincipalName());
240                     requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI,
241                             null));
242                     throw new ProfileException("User failed authentication");
243                 }
244             }
245
246             resolveAttributes(requestContext);
247
248             ArrayList<Statement> statements = new ArrayList<Statement>();
249             statements.add(buildAuthnStatement(requestContext));
250             if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
251                 AttributeStatement attributeStatement = buildAttributeStatement(requestContext);
252                 if (attributeStatement != null) {
253                     requestContext.setReleasedAttributes(requestContext.getAttributes().keySet());
254                     statements.add(attributeStatement);
255                 }
256             }
257
258             samlResponse = buildResponse(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:bearer", statements);
259         } catch (ProfileException e) {
260             samlResponse = buildErrorResponse(requestContext);
261         }
262
263         requestContext.setOutboundSAMLMessage(samlResponse);
264         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
265         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
266         encodeResponse(requestContext);
267         writeAuditLogEntry(requestContext);
268     }
269
270     /**
271      * Decodes an incoming request and stores the information in a created request context.
272      * 
273      * @param inTransport inbound transport
274      * @param outTransport outbound transport
275      * @param requestContext request context to which decoded information should be added
276      * 
277      * @throws ProfileException thrown if the incoming message failed decoding
278      */
279     protected void decodeRequest(SSORequestContext requestContext, HTTPInTransport inTransport,
280             HTTPOutTransport outTransport) throws ProfileException {
281         log.debug("Decoding message with decoder binding '{}'", getInboundBinding());
282
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 from relying party '{}'", requestContext.getInboundMessageIssuer());
301
302             if (!(requestContext.getInboundSAMLMessage() instanceof AuthnRequest)) {
303                 log.warn("Incomming message was not a AuthnRequest, it was a '{}'",
304                         requestContext.getInboundSAMLMessage().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         } catch (MessageDecodingException e) {
310             String msg = "Error decoding authentication request message"; 
311             log.warn(msg, e);
312             throw new ProfileException(msg, e);
313         } catch (SecurityException e) {
314             String msg = "Message did not meet security requirements"; 
315             log.warn(msg, e);
316             throw new ProfileException(msg, 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 = deserializeRequest(loginContext.getAuthenticationRequest());
401             requestContext.setInboundMessage(authnRequest);
402             requestContext.setInboundSAMLMessage(authnRequest);
403             requestContext.setInboundSAMLMessageId(authnRequest.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         long maxSPSessionLifetime = requestContext.getProfileConfiguration().getMaximumSPSessionLifetime();
439         if (maxSPSessionLifetime > 0) {
440             DateTime lifetime = new DateTime(DateTimeZone.UTC).plus(maxSPSessionLifetime);
441             log.debug("Explicitly setting SP session expiration time to '{}'", lifetime.toString());
442             statement.setSessionNotOnOrAfter(lifetime);
443         }
444
445         statement.setSubjectLocality(buildSubjectLocality(requestContext));
446
447         return statement;
448     }
449
450     /**
451      * Creates an {@link AuthnContext} for a successful authentication request.
452      * 
453      * @param requestContext current request
454      * 
455      * @return the built authn context
456      */
457     protected AuthnContext buildAuthnContext(SSORequestContext requestContext) {
458         AuthnContext authnContext = authnContextBuilder.buildObject();
459
460         Saml2LoginContext loginContext = requestContext.getLoginContext();
461         AuthnRequest authnRequest = requestContext.getInboundSAMLMessage();
462         RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
463         if (requestedAuthnContext != null) {
464             if (requestedAuthnContext.getAuthnContextClassRefs() != null) {
465                 for (AuthnContextClassRef classRef : requestedAuthnContext.getAuthnContextClassRefs()) {
466                     if (classRef.getAuthnContextClassRef().equals(loginContext.getAuthenticationMethod())) {
467                         AuthnContextClassRef ref = authnContextClassRefBuilder.buildObject();
468                         ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
469                         authnContext.setAuthnContextClassRef(ref);
470                     }
471                 }
472             } else if (requestedAuthnContext.getAuthnContextDeclRefs() != null) {
473                 for (AuthnContextDeclRef declRef : requestedAuthnContext.getAuthnContextDeclRefs()) {
474                     if (declRef.getAuthnContextDeclRef().equals(loginContext.getAuthenticationMethod())) {
475                         AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
476                         ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
477                         authnContext.setAuthnContextDeclRef(ref);
478                     }
479                 }
480             }
481         }
482         
483         if(authnContext.getAuthnContextClassRef() == null || authnContext.getAuthnContextDeclRef() == null){
484             AuthnContextClassRef ref = authnContextClassRefBuilder.buildObject();
485             ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
486             authnContext.setAuthnContextClassRef(ref);
487         }
488
489         return authnContext;
490     }
491
492     /**
493      * Constructs the subject locality for the authentication statement.
494      * 
495      * @param requestContext curent request context
496      * 
497      * @return subject locality for the authentication statement
498      */
499     protected SubjectLocality buildSubjectLocality(SSORequestContext requestContext) {
500         HTTPInTransport transport = (HTTPInTransport) requestContext.getInboundMessageTransport();
501         SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
502         subjectLocality.setAddress(transport.getPeerAddress());
503
504         return subjectLocality;
505     }
506
507     /**
508      * Selects the appropriate endpoint for the relying party and stores it in the request context.
509      * 
510      * @param requestContext current request context
511      * 
512      * @return Endpoint selected from the information provided in the request context
513      */
514     protected Endpoint selectEndpoint(BaseSAMLProfileRequestContext requestContext) {
515         AuthnRequest authnRequest = ((SSORequestContext) requestContext).getInboundSAMLMessage();
516
517         Endpoint endpoint = null;
518         if (requestContext.getRelyingPartyConfiguration().getRelyingPartyId() == SAMLMDRelyingPartyConfigurationManager.ANONYMOUS_RP_NAME) {
519             if (authnRequest.getAssertionConsumerServiceURL() != null) {
520                 endpoint = endpointBuilder.buildObject();
521                 endpoint.setLocation(authnRequest.getAssertionConsumerServiceURL());
522                 if (authnRequest.getProtocolBinding() != null) {
523                     endpoint.setBinding(authnRequest.getProtocolBinding());
524                 } else {
525                     endpoint.setBinding(getSupportedOutboundBindings().get(0));
526                 }
527                 log.warn("Generating endpoint for anonymous relying party. ACS url '{}' and binding '{}'", new Object[] {
528                         requestContext.getInboundMessageIssuer(), endpoint.getLocation(), endpoint.getBinding(), });
529             } else {
530                 log.warn("Unable to generate endpoint for anonymous party.  No ACS url provided.");
531             }
532         } else {
533             AuthnResponseEndpointSelector endpointSelector = new AuthnResponseEndpointSelector();
534             endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
535             endpointSelector.setMetadataProvider(getMetadataProvider());
536             endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
537             endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
538             endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
539             endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
540             endpoint = endpointSelector.selectEndpoint();
541         }
542
543         return endpoint;
544     }
545
546     /**
547      * Deserailizes an authentication request from a string.
548      * 
549      * @param request request to deserialize
550      * 
551      * @return the request XMLObject
552      * 
553      * @throws UnmarshallingException thrown if the request can no be deserialized and unmarshalled
554      */
555     protected AuthnRequest deserializeRequest(String request) throws UnmarshallingException {
556         try {
557             Element requestElem = getParserPool().parse(new StringReader(request)).getDocumentElement();
558             Unmarshaller unmarshaller = Configuration.getUnmarshallerFactory().getUnmarshaller(requestElem);
559             return (AuthnRequest) unmarshaller.unmarshall(requestElem);
560         } catch (Exception e) {
561             throw new UnmarshallingException("Unable to read serialized authentication request");
562         }
563     }
564
565     /** Represents the internal state of a SAML 2.0 SSO Request while it's being processed by the IdP. */
566     protected class SSORequestContext extends BaseSAML2ProfileRequestContext<AuthnRequest, Response, SSOConfiguration> {
567
568         /** Current login context. */
569         private Saml2LoginContext loginContext;
570
571         /**
572          * Gets the current login context.
573          * 
574          * @return current login context
575          */
576         public Saml2LoginContext getLoginContext() {
577             return loginContext;
578         }
579
580         /**
581          * Sets the current login context.
582          * 
583          * @param context current login context
584          */
585         public void setLoginContext(Saml2LoginContext context) {
586             loginContext = context;
587         }
588     }
589 }