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