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 '{}'", requestContext.getInboundMessageIssuer());
    173                 log.warn(msg);
    174                 throw new ProfileException(msg);
    175             }
    176
    177             log.debug("Creating login context and transferring control to authentication engine");
    178             Saml2LoginContext loginContext = new Saml2LoginContext(relyingPartyId, requestContext.getRelayState(),
    179                     requestContext.getInboundSAMLMessage());
    180             loginContext.setAuthenticationEngineURL(authenticationManagerPath);
    181             loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(servletRequest));
    182             loginContext.setDefaultAuthenticationMethod(rpConfig.getDefaultAuthenticationMethod());
    183
    184             HttpServletHelper.bindLoginContext(loginContext, servletRequest);
    185             RequestDispatcher dispatcher = servletRequest.getRequestDispatcher(authenticationManagerPath);
    186             dispatcher.forward(servletRequest, ((HttpServletResponseAdapter) outTransport).getWrappedResponse());
    187         } catch (MarshallingException e) {
    188             log.error("Unable to marshall authentication request context");
    189             throw new ProfileException("Unable to marshall authentication request context", e);
    190         } catch (IOException ex) {
    191             log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
    192             throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
    193         } catch (ServletException ex) {
    194             log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
    195             throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
    196         }
    197     }
    198
    199     /**
    200      * Creates a response to the {@link AuthnRequest} and sends the user, with response in tow, back to the relying
    201      * party after they've been authenticated.
    202      *
    203      * @param inTransport inbound message transport
    204      * @param outTransport outbound message transport
    205      *
    206      * @throws ProfileException thrown if the response can not be created and sent back to the relying party
    207      */
    208     protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
    209             throws ProfileException {
    210         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
    211         Saml2LoginContext loginContext = (Saml2LoginContext) HttpServletHelper.getLoginContext(httpRequest);
    212
    213         SSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
    214
    215         checkSamlVersion(requestContext);
    216
    217         Response samlResponse;
    218         try {
    219             if (loginContext.getAuthenticationFailure() != null) {
    220                 if (loginContext.getAuthenticationFailure() instanceof PassiveAuthenticationException) {
    221                     requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.NO_PASSIVE_URI,
    222                             null));
    223                 } else {
    224                     requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI,
    225                             null));
    226                 }
    227                 throw new ProfileException("Authentication failure", loginContext.getAuthenticationFailure());
    228             }
    229
    230             if (requestContext.getSubjectNameIdentifier() != null) {
    231                 log
    232                         .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
    237                             .warn(
    238                                     "Authentication request identified principal {} but authentication mechanism identified principal {}",
    239                                     requestedPrincipalName, loginContext.getPrincipalName());
    240                     requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI,
    241                             null));
    242                     throw new ProfileException("User failed authentication");
    243                 }
    244             }
    245
    246             resolveAttributes(requestContext);
    247
    248             ArrayList<Statement> statements = new ArrayList<Statement>();
    249             statements.add(buildAuthnStatement(requestContext));
    250             if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
    251                 AttributeStatement attributeStatement = buildAttributeStatement(requestContext);
    252                 if (attributeStatement != null) {
    253                     requestContext.setReleasedAttributes(requestContext.getAttributes().keySet());
    254                     statements.add(attributeStatement);
    255                 }
    256             }
    257
    258             samlResponse = buildResponse(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:bearer", statements);
    259         } catch (ProfileException e) {
    260             samlResponse = buildErrorResponse(requestContext);
    261         }
    262
    263         requestContext.setOutboundSAMLMessage(samlResponse);
    264         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
    265         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
    266         encodeResponse(requestContext);
    267         writeAuditLogEntry(requestContext);
    268     }
    269
    270     /**
    271      * Decodes an incoming request and stores the information in a created request context.
    272      *
    273      * @param inTransport inbound transport
    274      * @param outTransport outbound transport
    275      * @param requestContext request context to which decoded information should be added
    276      *
    277      * @throws ProfileException thrown if the incoming message failed decoding
    278      */
    279     protected void decodeRequest(SSORequestContext requestContext, HTTPInTransport inTransport,
    280             HTTPOutTransport outTransport) throws ProfileException {
    281         if (log.isDebugEnabled()) {
    282             log.debug("Decoding message with decoder binding '{}'",
    283                     getInboundMessageDecoder(requestContext).getBindingURI());
    284         }
    285
    286         requestContext.setCommunicationProfileId(getProfileId());
    287
    288         requestContext.setMetadataProvider(getMetadataProvider());
    289         requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
    290
    291         requestContext.setCommunicationProfileId(getProfileId());
    292         requestContext.setInboundMessageTransport(inTransport);
    293         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
    294         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
    295
    296         requestContext.setOutboundMessageTransport(outTransport);
    297         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
    298
    299         try {
    300             SAMLMessageDecoder decoder = getInboundMessageDecoder(requestContext);
    301             requestContext.setMessageDecoder(decoder);
    302             decoder.decode(requestContext);
    303             log.debug("Decoded request from relying party '{}'", requestContext.getInboundMessageIssuer());
    304
    305             if (!(requestContext.getInboundSAMLMessage() instanceof AuthnRequest)) {
    306                 log.warn("Incomming message was not a AuthnRequest, it was a '{}'",
    307                         requestContext.getInboundSAMLMessage().getClass().getName());
    308                 requestContext.setFailureStatus(buildStatus(StatusCode.REQUESTER_URI, null,
    309                         "Invalid SAML AuthnRequest message."));
    310                 throw new ProfileException("Invalid SAML AuthnRequest message.");
    311             }
    312         } catch (MessageDecodingException e) {
    313             String msg = "Error decoding authentication request message";
    314             log.warn(msg, e);
    315             throw new ProfileException(msg, e);
    316         } catch (SecurityException e) {
    317             String msg = "Message did not meet security requirements";
    318             log.warn(msg, e);
    319             throw new ProfileException(msg, e);
    320         }
    321     }
    322
    323     /**
    324      * Creates an authentication request context from the current environmental information.
    325      *
    326      * @param loginContext current login context
    327      * @param in inbound transport
    328      * @param out outbount transport
    329      *
    330      * @return created authentication request context
    331      *
    332      * @throws ProfileException thrown if there is a problem creating the context
    333      */
    334     protected SSORequestContext buildRequestContext(Saml2LoginContext loginContext, HTTPInTransport in,
    335             HTTPOutTransport out) throws ProfileException {
    336         SSORequestContext requestContext = new SSORequestContext();
    337         requestContext.setCommunicationProfileId(getProfileId());
    338
    339         requestContext.setMessageDecoder(getInboundMessageDecoder(requestContext));
    340
    341         requestContext.setLoginContext(loginContext);
    342
    343         requestContext.setInboundMessageTransport(in);
    344         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
    345
    346         requestContext.setOutboundMessageTransport(out);
    347         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
    348
    349         requestContext.setMetadataProvider(getMetadataProvider());
    350
    351         String relyingPartyId = loginContext.getRelyingPartyId();
    352         requestContext.setPeerEntityId(relyingPartyId);
    353         requestContext.setInboundMessageIssuer(relyingPartyId);
    354
    355         populateRequestContext(requestContext);
    356
    357         return requestContext;
    358     }
    359
    360     /** {@inheritDoc} */
    361     protected void populateRelyingPartyInformation(BaseSAMLProfileRequestContext requestContext)
    362             throws ProfileException {
    363         super.populateRelyingPartyInformation(requestContext);
    364
    365         EntityDescriptor relyingPartyMetadata = requestContext.getPeerEntityMetadata();
    366         if (relyingPartyMetadata != null) {
    367             requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
    368             requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS));
    369         }
    370     }
    371
    372     /** {@inheritDoc} */
    373     protected void populateAssertingPartyInformation(BaseSAMLProfileRequestContext requestContext)
    374             throws ProfileException {
    375         super.populateAssertingPartyInformation(requestContext);
    376
    377         EntityDescriptor localEntityDescriptor = requestContext.getLocalEntityMetadata();
    378         if (localEntityDescriptor != null) {
    379             requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
    380             requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
    381                     .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
    382         }
    383     }
    384
    385     /**
    386      * Populates the request context with information from the inbound SAML message.
    387      *
    388      * This method requires the the following request context properties to be populated: login context
    389      *
    390      * This methods populates the following request context properties: inbound saml message, relay state, inbound saml
    391      * message ID, subject name identifier
    392      *
    393      * @param requestContext current request context
    394      *
    395      * @throws ProfileException thrown if the inbound SAML message or subject identifier is null
    396      */
    397     protected void populateSAMLMessageInformation(BaseSAMLProfileRequestContext requestContext) throws ProfileException {
    398         SSORequestContext ssoRequestContext = (SSORequestContext) requestContext;
    399         try {
    400             Saml2LoginContext loginContext = ssoRequestContext.getLoginContext();
    401             requestContext.setRelayState(loginContext.getRelayState());
    402
    403             AuthnRequest authnRequest = deserializeRequest(loginContext.getAuthenticationRequest());
    404             requestContext.setInboundMessage(authnRequest);
    405             requestContext.setInboundSAMLMessage(authnRequest);
    406             requestContext.setInboundSAMLMessageId(authnRequest.getID());
    407
    408             Subject authnSubject = authnRequest.getSubject();
    409             if (authnSubject != null) {
    410                 requestContext.setSubjectNameIdentifier(authnSubject.getNameID());
    411             }
    412         } catch (UnmarshallingException e) {
    413             log.error("Unable to unmarshall authentication request context");
    414             ssoRequestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
    415                     "Error recovering request state"));
    416             throw new ProfileException("Error recovering request state", e);
    417         }
    418     }
    419
    420     /**
    421      * Creates an authentication statement for the current request.
    422      *
    423      * @param requestContext current request context
    424      *
    425      * @return constructed authentication statement
    426      */
    427     protected AuthnStatement buildAuthnStatement(SSORequestContext requestContext) {
    428         Saml2LoginContext loginContext = requestContext.getLoginContext();
    429
    430         AuthnContext authnContext = buildAuthnContext(requestContext);
    431
    432         AuthnStatement statement = authnStatementBuilder.buildObject();
    433         statement.setAuthnContext(authnContext);
    434         statement.setAuthnInstant(loginContext.getAuthenticationInstant());
    435
    436         Session session = getUserSession(requestContext.getInboundMessageTransport());
    437         if (session != null) {
    438             statement.setSessionIndex(session.getSessionID());
    439         }
    440
    441         long maxSPSessionLifetime = requestContext.getProfileConfiguration().getMaximumSPSessionLifetime();
    442         if (maxSPSessionLifetime > 0) {
    443             DateTime lifetime = new DateTime(DateTimeZone.UTC).plus(maxSPSessionLifetime);
    444             log.debug("Explicitly setting SP session expiration time to '{}'", lifetime.toString());
    445             statement.setSessionNotOnOrAfter(lifetime);
    446         }
    447
    448         statement.setSubjectLocality(buildSubjectLocality(requestContext));
    449
    450         return statement;
    451     }
    452
    453     /**
    454      * Creates an {@link AuthnContext} for a successful authentication request.
    455      *
    456      * @param requestContext current request
    457      *
    458      * @return the built authn context
    459      */
    460     protected AuthnContext buildAuthnContext(SSORequestContext requestContext) {
    461         AuthnContext authnContext = authnContextBuilder.buildObject();
    462
    463         Saml2LoginContext loginContext = requestContext.getLoginContext();
    464         AuthnRequest authnRequest = requestContext.getInboundSAMLMessage();
    465         RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
    466         if (requestedAuthnContext != null) {
    467             if (requestedAuthnContext.getAuthnContextClassRefs() != null) {
    468                 for (AuthnContextClassRef classRef : requestedAuthnContext.getAuthnContextClassRefs()) {
    469                     if (classRef.getAuthnContextClassRef().equals(loginContext.getAuthenticationMethod())) {
    470                         AuthnContextClassRef ref = authnContextClassRefBuilder.buildObject();
    471                         ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
    472                         authnContext.setAuthnContextClassRef(ref);
    473                     }
    474                 }
    475             } else if (requestedAuthnContext.getAuthnContextDeclRefs() != null) {
    476                 for (AuthnContextDeclRef declRef : requestedAuthnContext.getAuthnContextDeclRefs()) {
    477                     if (declRef.getAuthnContextDeclRef().equals(loginContext.getAuthenticationMethod())) {
    478                         AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
    479                         ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
    480                         authnContext.setAuthnContextDeclRef(ref);
    481                     }
    482                 }
    483             }
    484         }
    485
    486         if(authnContext.getAuthnContextClassRef() == null || authnContext.getAuthnContextDeclRef() == null){
    487             AuthnContextClassRef ref = authnContextClassRefBuilder.buildObject();
    488             ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
    489             authnContext.setAuthnContextClassRef(ref);
    490         }
    491
    492         return authnContext;
    493     }
    494
    495     /**
    496      * Constructs the subject locality for the authentication statement.
    497      *
    498      * @param requestContext curent request context
    499      *
    500      * @return subject locality for the authentication statement
    501      */
    502     protected SubjectLocality buildSubjectLocality(SSORequestContext requestContext) {
    503         HTTPInTransport transport = (HTTPInTransport) requestContext.getInboundMessageTransport();
    504         SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
    505         subjectLocality.setAddress(transport.getPeerAddress());
    506
    507         return subjectLocality;
    508     }
    509
    510     /**
    511      * Selects the appropriate endpoint for the relying party and stores it in the request context.
    512      *
    513      * @param requestContext current request context
    514      *
    515      * @return Endpoint selected from the information provided in the request context
    516      */
    517     protected Endpoint selectEndpoint(BaseSAMLProfileRequestContext requestContext) {
    518         AuthnRequest authnRequest = ((SSORequestContext) requestContext).getInboundSAMLMessage();
    519
    520         Endpoint endpoint = null;
    521         if (requestContext.getRelyingPartyConfiguration().getRelyingPartyId() == SAMLMDRelyingPartyConfigurationManager.ANONYMOUS_RP_NAME) {
    522             if (authnRequest.getAssertionConsumerServiceURL() != null) {
    523                 endpoint = endpointBuilder.buildObject();
    524                 endpoint.setLocation(authnRequest.getAssertionConsumerServiceURL());
    525                 if (authnRequest.getProtocolBinding() != null) {
    526                     endpoint.setBinding(authnRequest.getProtocolBinding());
    527                 } else {
    528                     endpoint.setBinding(getSupportedOutboundBindings().get(0));
    529                 }
    530                 log.warn("Generating endpoint for anonymous relying party self-identified as '{}', ACS url '{}' and binding '{}'",
    531                         new Object[] {requestContext.getInboundMessageIssuer(), endpoint.getLocation(), endpoint.getBinding(), });
    532             } else {
    533                 log.warn("Unable to generate endpoint for anonymous party.  No ACS url provided.");
    534             }
    535         } else {
    536             AuthnResponseEndpointSelector endpointSelector = new AuthnResponseEndpointSelector();
    537             endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
    538             endpointSelector.setMetadataProvider(getMetadataProvider());
    539             endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
    540             endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
    541             endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
    542             endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
    543             endpoint = endpointSelector.selectEndpoint();
    544         }
    545
    546         return endpoint;
    547     }
    548
    549     /**
    550      * Deserailizes an authentication request from a string.
    551      *
    552      * @param request request to deserialize
    553      *
    554      * @return the request XMLObject
    555      *
    556      * @throws UnmarshallingException thrown if the request can no be deserialized and unmarshalled
    557      */
    558     protected AuthnRequest deserializeRequest(String request) throws UnmarshallingException {
    559         try {
    560             Element requestElem = getParserPool().parse(new StringReader(request)).getDocumentElement();
    561             Unmarshaller unmarshaller = Configuration.getUnmarshallerFactory().getUnmarshaller(requestElem);
    562             return (AuthnRequest) unmarshaller.unmarshall(requestElem);
    563         } catch (Exception e) {
    564             throw new UnmarshallingException("Unable to read serialized authentication request");
    565         }
    566     }
    567
    568     /** Represents the internal state of a SAML 2.0 SSO Request while it's being processed by the IdP. */
    569     protected class SSORequestContext extends BaseSAML2ProfileRequestContext<AuthnRequest, Response, SSOConfiguration> {
    570
    571         /** Current login context. */
    572         private Saml2LoginContext loginContext;
    573
    574         /**
    575          * Gets the current login context.
    576          *
    577          * @return current login context
    578          */
    579         public Saml2LoginContext getLoginContext() {
    580             return loginContext;
    581         }
    582
    583         /**
    584          * Sets the current login context.
    585          *
    586          * @param context current login context
    587          */
    588         public void setLoginContext(Saml2LoginContext context) {
    589             loginContext = context;
    590         }
    591     }
    592 }