Add SPNameQualifier to returned NameIDs if present in request
[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         NameIDPolicy nameIdPolcy = request.getNameIDPolicy();
342         String spNameQualifier = null;
343         if (nameIdPolcy != null) {
344             spNameQualifier = DatatypeHelper.safeTrimOrNullString(nameIdPolcy.getSPNameQualifier());
345             if (spNameQualifier == null) {
346                 return;
347             }
348         }
349
350         log.debug("Checking if message issuer is a member of affiliation '{}'", spNameQualifier);
351         try {
352             EntityDescriptor affiliation = getMetadataProvider().getEntityDescriptor(spNameQualifier);
353             if (affiliation != null) {
354                 AffiliationDescriptor affiliationDescriptor = affiliation.getAffiliationDescriptor();
355                 if (affiliationDescriptor != null && affiliationDescriptor.getMembers() != null) {
356                     for (AffiliateMember member : affiliationDescriptor.getMembers()) {
357                         if (DatatypeHelper.safeEquals(member.getID(), requestContext.getInboundMessageIssuer())) {
358                             return;
359                         }
360                     }
361                 }
362             }
363
364             requestContext.setFailureStatus(buildStatus(StatusCode.REQUESTER_URI, StatusCode.INVALID_NAMEID_POLICY_URI,
365                     "Invalid SPNameQualifier for this request"));
366             throw new ProfileException(MessageFormatter.format(
367                     "Relying party '{}' is not a member of the affiliation '{}'", requestContext
368                             .getInboundMessageIssuer(), spNameQualifier));
369         } catch (MetadataProviderException e) {
370             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Internal service error"));
371             log.error("Error looking up metadata for affiliation", e);
372             throw new ProfileException(MessageFormatter.format(
373                     "Relying party '{}' is not a member of the affiliation '{}'", requestContext
374                             .getInboundMessageIssuer(), spNameQualifier));
375         }
376     }
377
378     /**
379      * Creates an authentication request context from the current environmental information.
380      * 
381      * @param loginContext current login context
382      * @param in inbound transport
383      * @param out outbount transport
384      * 
385      * @return created authentication request context
386      * 
387      * @throws ProfileException thrown if there is a problem creating the context
388      */
389     protected SSORequestContext buildRequestContext(Saml2LoginContext loginContext, HTTPInTransport in,
390             HTTPOutTransport out) throws ProfileException {
391         SSORequestContext requestContext = new SSORequestContext();
392         requestContext.setCommunicationProfileId(getProfileId());
393
394         requestContext.setMessageDecoder(getInboundMessageDecoder(requestContext));
395
396         requestContext.setLoginContext(loginContext);
397
398         requestContext.setInboundMessageTransport(in);
399         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
400
401         requestContext.setOutboundMessageTransport(out);
402         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
403
404         requestContext.setMetadataProvider(getMetadataProvider());
405
406         String relyingPartyId = loginContext.getRelyingPartyId();
407         requestContext.setPeerEntityId(relyingPartyId);
408         requestContext.setInboundMessageIssuer(relyingPartyId);
409
410         populateRequestContext(requestContext);
411
412         return requestContext;
413     }
414
415     /** {@inheritDoc} */
416     protected void populateRelyingPartyInformation(BaseSAMLProfileRequestContext requestContext)
417             throws ProfileException {
418         super.populateRelyingPartyInformation(requestContext);
419
420         EntityDescriptor relyingPartyMetadata = requestContext.getPeerEntityMetadata();
421         if (relyingPartyMetadata != null) {
422             requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
423             requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS));
424         }
425     }
426
427     /** {@inheritDoc} */
428     protected void populateAssertingPartyInformation(BaseSAMLProfileRequestContext requestContext)
429             throws ProfileException {
430         super.populateAssertingPartyInformation(requestContext);
431
432         EntityDescriptor localEntityDescriptor = requestContext.getLocalEntityMetadata();
433         if (localEntityDescriptor != null) {
434             requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
435             requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
436                     .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
437         }
438     }
439
440     /**
441      * Populates the request context with information from the inbound SAML message.
442      * 
443      * This method requires the the following request context properties to be populated: login context
444      * 
445      * This methods populates the following request context properties: inbound saml message, relay state, inbound saml
446      * message ID, subject name identifier
447      * 
448      * @param requestContext current request context
449      * 
450      * @throws ProfileException thrown if the inbound SAML message or subject identifier is null
451      */
452     protected void populateSAMLMessageInformation(BaseSAMLProfileRequestContext requestContext) throws ProfileException {
453         SSORequestContext ssoRequestContext = (SSORequestContext) requestContext;
454         try {
455             Saml2LoginContext loginContext = ssoRequestContext.getLoginContext();
456             requestContext.setRelayState(loginContext.getRelayState());
457
458             AuthnRequest authnRequest = deserializeRequest(loginContext.getAuthenticationRequest());
459             requestContext.setInboundMessage(authnRequest);
460             requestContext.setInboundSAMLMessage(authnRequest);
461             requestContext.setInboundSAMLMessageId(authnRequest.getID());
462
463             Subject authnSubject = authnRequest.getSubject();
464             if (authnSubject != null) {
465                 requestContext.setSubjectNameIdentifier(authnSubject.getNameID());
466             }
467         } catch (UnmarshallingException e) {
468             log.error("Unable to unmarshall authentication request context");
469             ssoRequestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
470                     "Error recovering request state"));
471             throw new ProfileException("Error recovering request state", e);
472         }
473     }
474
475     /**
476      * Creates an authentication statement for the current request.
477      * 
478      * @param requestContext current request context
479      * 
480      * @return constructed authentication statement
481      */
482     protected AuthnStatement buildAuthnStatement(SSORequestContext requestContext) {
483         Saml2LoginContext loginContext = requestContext.getLoginContext();
484
485         AuthnContext authnContext = buildAuthnContext(requestContext);
486
487         AuthnStatement statement = authnStatementBuilder.buildObject();
488         statement.setAuthnContext(authnContext);
489         statement.setAuthnInstant(loginContext.getAuthenticationInstant());
490
491         Session session = getUserSession(requestContext.getInboundMessageTransport());
492         if (session != null) {
493             statement.setSessionIndex(session.getSessionID());
494         }
495
496         long maxSPSessionLifetime = requestContext.getProfileConfiguration().getMaximumSPSessionLifetime();
497         if (maxSPSessionLifetime > 0) {
498             DateTime lifetime = new DateTime(DateTimeZone.UTC).plus(maxSPSessionLifetime);
499             log.debug("Explicitly setting SP session expiration time to '{}'", lifetime.toString());
500             statement.setSessionNotOnOrAfter(lifetime);
501         }
502
503         statement.setSubjectLocality(buildSubjectLocality(requestContext));
504
505         return statement;
506     }
507
508     /**
509      * Creates an {@link AuthnContext} for a successful authentication request.
510      * 
511      * @param requestContext current request
512      * 
513      * @return the built authn context
514      */
515     protected AuthnContext buildAuthnContext(SSORequestContext requestContext) {
516         AuthnContext authnContext = authnContextBuilder.buildObject();
517
518         Saml2LoginContext loginContext = requestContext.getLoginContext();
519         AuthnRequest authnRequest = requestContext.getInboundSAMLMessage();
520         RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
521         if (requestedAuthnContext != null) {
522             if (requestedAuthnContext.getAuthnContextClassRefs() != null) {
523                 for (AuthnContextClassRef classRef : requestedAuthnContext.getAuthnContextClassRefs()) {
524                     if (classRef.getAuthnContextClassRef().equals(loginContext.getAuthenticationMethod())) {
525                         AuthnContextClassRef ref = authnContextClassRefBuilder.buildObject();
526                         ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
527                         authnContext.setAuthnContextClassRef(ref);
528                     }
529                 }
530             } else if (requestedAuthnContext.getAuthnContextDeclRefs() != null) {
531                 for (AuthnContextDeclRef declRef : requestedAuthnContext.getAuthnContextDeclRefs()) {
532                     if (declRef.getAuthnContextDeclRef().equals(loginContext.getAuthenticationMethod())) {
533                         AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
534                         ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
535                         authnContext.setAuthnContextDeclRef(ref);
536                     }
537                 }
538             }
539         }
540
541         if (authnContext.getAuthnContextClassRef() == null || authnContext.getAuthnContextDeclRef() == null) {
542             AuthnContextClassRef ref = authnContextClassRefBuilder.buildObject();
543             ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
544             authnContext.setAuthnContextClassRef(ref);
545         }
546
547         return authnContext;
548     }
549
550     /**
551      * Constructs the subject locality for the authentication statement.
552      * 
553      * @param requestContext curent request context
554      * 
555      * @return subject locality for the authentication statement
556      */
557     protected SubjectLocality buildSubjectLocality(SSORequestContext requestContext) {
558         HTTPInTransport transport = (HTTPInTransport) requestContext.getInboundMessageTransport();
559         SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
560         subjectLocality.setAddress(transport.getPeerAddress());
561
562         return subjectLocality;
563     }
564     
565     /** {@inheritDoc} */
566     protected NameID buildNameId(BaseSAML2ProfileRequestContext requestContext) throws ProfileException {
567         NameID nameId = super.buildNameId(requestContext);
568         
569         AuthnRequest authnRequest = (AuthnRequest) requestContext.getInboundMessage();
570         NameIDPolicy nameIdPolicy = authnRequest.getNameIDPolicy();
571         if(nameIdPolicy != null){
572             if(!DatatypeHelper.isEmpty(nameIdPolicy.getSPNameQualifier())){
573                 nameId.setSPNameQualifier(nameIdPolicy.getSPNameQualifier());
574             }
575         }
576         
577         return nameId;
578     }
579
580     /**
581      * Selects the appropriate endpoint for the relying party and stores it in the request context.
582      * 
583      * @param requestContext current request context
584      * 
585      * @return Endpoint selected from the information provided in the request context
586      */
587     protected Endpoint selectEndpoint(BaseSAMLProfileRequestContext requestContext) {
588         AuthnRequest authnRequest = ((SSORequestContext) requestContext).getInboundSAMLMessage();
589
590         Endpoint endpoint = null;
591         if (requestContext.getRelyingPartyConfiguration().getRelyingPartyId() == SAMLMDRelyingPartyConfigurationManager.ANONYMOUS_RP_NAME) {
592             if (authnRequest.getAssertionConsumerServiceURL() != null) {
593                 endpoint = endpointBuilder.buildObject();
594                 endpoint.setLocation(authnRequest.getAssertionConsumerServiceURL());
595                 if (authnRequest.getProtocolBinding() != null) {
596                     endpoint.setBinding(authnRequest.getProtocolBinding());
597                 } else {
598                     endpoint.setBinding(getSupportedOutboundBindings().get(0));
599                 }
600                 log
601                         .warn(
602                                 "Generating endpoint for anonymous relying party self-identified as '{}', ACS url '{}' and binding '{}'",
603                                 new Object[] { requestContext.getInboundMessageIssuer(), endpoint.getLocation(),
604                                         endpoint.getBinding(), });
605             } else {
606                 log.warn("Unable to generate endpoint for anonymous party.  No ACS url provided.");
607             }
608         } else {
609             AuthnResponseEndpointSelector endpointSelector = new AuthnResponseEndpointSelector();
610             endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
611             endpointSelector.setMetadataProvider(getMetadataProvider());
612             endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
613             endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
614             endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
615             endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
616             endpoint = endpointSelector.selectEndpoint();
617         }
618
619         return endpoint;
620     }
621
622     /**
623      * Deserailizes an authentication request from a string.
624      * 
625      * @param request request to deserialize
626      * 
627      * @return the request XMLObject
628      * 
629      * @throws UnmarshallingException thrown if the request can no be deserialized and unmarshalled
630      */
631     protected AuthnRequest deserializeRequest(String request) throws UnmarshallingException {
632         try {
633             Element requestElem = getParserPool().parse(new StringReader(request)).getDocumentElement();
634             Unmarshaller unmarshaller = Configuration.getUnmarshallerFactory().getUnmarshaller(requestElem);
635             return (AuthnRequest) unmarshaller.unmarshall(requestElem);
636         } catch (Exception e) {
637             throw new UnmarshallingException("Unable to read serialized authentication request");
638         }
639     }
640
641     /** Represents the internal state of a SAML 2.0 SSO Request while it's being processed by the IdP. */
642     protected class SSORequestContext extends BaseSAML2ProfileRequestContext<AuthnRequest, Response, SSOConfiguration> {
643
644         /** Current login context. */
645         private Saml2LoginContext loginContext;
646
647         /**
648          * Gets the current login context.
649          * 
650          * @return current login context
651          */
652         public Saml2LoginContext getLoginContext() {
653             return loginContext;
654         }
655
656         /**
657          * Sets the current login context.
658          * 
659          * @param context current login context
660          */
661         public void setLoginContext(Saml2LoginContext context) {
662             loginContext = context;
663         }
664     }
665 }