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