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