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