View Javadoc

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