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