2 * Copyright 2007 University Corporation for Advanced Internet Development, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package edu.internet2.middleware.shibboleth.idp.profile.saml2;
19 import java.io.IOException;
20 import java.io.StringReader;
21 import java.util.ArrayList;
23 import javax.servlet.ServletContext;
24 import javax.servlet.http.HttpServletRequest;
25 import javax.servlet.http.HttpServletResponse;
27 import org.joda.time.DateTime;
28 import org.joda.time.DateTimeZone;
29 import org.opensaml.Configuration;
30 import org.opensaml.common.SAMLObjectBuilder;
31 import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
32 import org.opensaml.common.xml.SAMLConstants;
33 import org.opensaml.saml2.binding.AuthnResponseEndpointSelector;
34 import org.opensaml.saml2.core.AttributeStatement;
35 import org.opensaml.saml2.core.AuthnContext;
36 import org.opensaml.saml2.core.AuthnContextClassRef;
37 import org.opensaml.saml2.core.AuthnContextDeclRef;
38 import org.opensaml.saml2.core.AuthnRequest;
39 import org.opensaml.saml2.core.AuthnStatement;
40 import org.opensaml.saml2.core.NameID;
41 import org.opensaml.saml2.core.NameIDPolicy;
42 import org.opensaml.saml2.core.RequestedAuthnContext;
43 import org.opensaml.saml2.core.Response;
44 import org.opensaml.saml2.core.Statement;
45 import org.opensaml.saml2.core.StatusCode;
46 import org.opensaml.saml2.core.Subject;
47 import org.opensaml.saml2.core.SubjectLocality;
48 import org.opensaml.saml2.metadata.AffiliateMember;
49 import org.opensaml.saml2.metadata.AffiliationDescriptor;
50 import org.opensaml.saml2.metadata.AssertionConsumerService;
51 import org.opensaml.saml2.metadata.Endpoint;
52 import org.opensaml.saml2.metadata.EntityDescriptor;
53 import org.opensaml.saml2.metadata.IDPSSODescriptor;
54 import org.opensaml.saml2.metadata.SPSSODescriptor;
55 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
56 import org.opensaml.ws.message.decoder.MessageDecodingException;
57 import org.opensaml.ws.transport.http.HTTPInTransport;
58 import org.opensaml.ws.transport.http.HTTPOutTransport;
59 import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
60 import org.opensaml.ws.transport.http.HttpServletResponseAdapter;
61 import org.opensaml.xml.io.MarshallingException;
62 import org.opensaml.xml.io.Unmarshaller;
63 import org.opensaml.xml.io.UnmarshallingException;
64 import org.opensaml.xml.security.SecurityException;
65 import org.opensaml.xml.util.DatatypeHelper;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
68 import org.w3c.dom.Element;
70 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
71 import edu.internet2.middleware.shibboleth.common.profile.provider.BaseSAMLProfileRequestContext;
72 import edu.internet2.middleware.shibboleth.common.relyingparty.ProfileConfiguration;
73 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
74 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.SAMLMDRelyingPartyConfigurationManager;
75 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.SSOConfiguration;
76 import edu.internet2.middleware.shibboleth.common.util.HttpHelper;
77 import edu.internet2.middleware.shibboleth.idp.authn.PassiveAuthenticationException;
78 import edu.internet2.middleware.shibboleth.idp.authn.Saml2LoginContext;
79 import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
80 import edu.internet2.middleware.shibboleth.idp.session.Session;
81 import edu.internet2.middleware.shibboleth.idp.util.HttpServletHelper;
83 /** SAML 2.0 SSO request profile handler. */
84 public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
87 private final Logger log = LoggerFactory.getLogger(SSOProfileHandler.class);
89 /** Builder of AuthnStatement objects. */
90 private SAMLObjectBuilder<AuthnStatement> authnStatementBuilder;
92 /** Builder of AuthnContext objects. */
93 private SAMLObjectBuilder<AuthnContext> authnContextBuilder;
95 /** Builder of AuthnContextClassRef objects. */
96 private SAMLObjectBuilder<AuthnContextClassRef> authnContextClassRefBuilder;
98 /** Builder of AuthnContextDeclRef objects. */
99 private SAMLObjectBuilder<AuthnContextDeclRef> authnContextDeclRefBuilder;
101 /** Builder of SubjectLocality objects. */
102 private SAMLObjectBuilder<SubjectLocality> subjectLocalityBuilder;
104 /** Builder of Endpoint objects. */
105 private SAMLObjectBuilder<Endpoint> endpointBuilder;
107 /** URL of the authentication manager Servlet. */
108 private String authenticationManagerPath;
113 * @param authnManagerPath path to the authentication manager Servlet
115 @SuppressWarnings("unchecked")
116 public SSOProfileHandler(String authnManagerPath) {
119 if (DatatypeHelper.isEmpty(authnManagerPath)) {
120 throw new IllegalArgumentException("Authentication manager path may not be null");
122 if (authnManagerPath.startsWith("/")) {
123 authenticationManagerPath = authnManagerPath;
125 authenticationManagerPath = "/" + authnManagerPath;
128 authnStatementBuilder = (SAMLObjectBuilder<AuthnStatement>) getBuilderFactory().getBuilder(
129 AuthnStatement.DEFAULT_ELEMENT_NAME);
130 authnContextBuilder = (SAMLObjectBuilder<AuthnContext>) getBuilderFactory().getBuilder(
131 AuthnContext.DEFAULT_ELEMENT_NAME);
132 authnContextClassRefBuilder = (SAMLObjectBuilder<AuthnContextClassRef>) getBuilderFactory().getBuilder(
133 AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
134 authnContextDeclRefBuilder = (SAMLObjectBuilder<AuthnContextDeclRef>) getBuilderFactory().getBuilder(
135 AuthnContextDeclRef.DEFAULT_ELEMENT_NAME);
136 subjectLocalityBuilder = (SAMLObjectBuilder<SubjectLocality>) getBuilderFactory().getBuilder(
137 SubjectLocality.DEFAULT_ELEMENT_NAME);
138 endpointBuilder = (SAMLObjectBuilder<Endpoint>) getBuilderFactory().getBuilder(
139 AssertionConsumerService.DEFAULT_ELEMENT_NAME);
143 public String getProfileId() {
144 return SSOConfiguration.PROFILE_ID;
148 public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
149 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
150 HttpServletResponse httpResponse = ((HttpServletResponseAdapter) outTransport).getWrappedResponse();
151 ServletContext servletContext = httpRequest.getSession().getServletContext();
153 LoginContext loginContext = HttpServletHelper.getLoginContext(getStorageService(),
154 servletContext, httpRequest);
155 if (loginContext == null || !(loginContext instanceof Saml2LoginContext)) {
156 log.debug("Incoming request does not contain a login context, processing as first leg of request");
157 performAuthentication(inTransport, outTransport);
158 } else if (loginContext.isPrincipalAuthenticated() || loginContext.getAuthenticationFailure() != null) {
159 log.debug("Incoming request contains a login context, processing as second leg of request");
160 HttpServletHelper.unbindLoginContext(getStorageService(), servletContext, httpRequest, httpResponse);
161 completeAuthenticationRequest((Saml2LoginContext)loginContext, inTransport, outTransport);
163 log.debug("Incoming request contained a login context but principal was not authenticated, processing as first leg of request");
164 performAuthentication(inTransport, outTransport);
169 * Creates a {@link Saml2LoginContext} an sends the request off to the AuthenticationManager to begin the process of
170 * authenticating the user.
172 * @param inTransport inbound request transport
173 * @param outTransport outbound response transport
175 * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
176 * authentication manager
178 protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
179 throws ProfileException {
180 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
181 HttpServletResponse httpResponse = ((HttpServletResponseAdapter) outTransport).getWrappedResponse();
183 SSORequestContext requestContext = new SSORequestContext();
186 decodeRequest(requestContext, inTransport, outTransport);
188 String relyingPartyId = requestContext.getInboundMessageIssuer();
189 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
190 ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(getProfileId());
191 if (ssoConfig == null) {
192 String msg = "SAML 2 SSO profile is not configured for relying party "
193 + requestContext.getInboundMessageIssuer();
195 throw new ProfileException(msg);
198 log.debug("Creating login context and transferring control to authentication engine");
199 Saml2LoginContext loginContext = new Saml2LoginContext(relyingPartyId, requestContext.getRelayState(),
200 requestContext.getInboundSAMLMessage());
201 loginContext.setAuthenticationEngineURL(authenticationManagerPath);
202 loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
203 loginContext.setDefaultAuthenticationMethod(rpConfig.getDefaultAuthenticationMethod());
205 HttpServletHelper.bindLoginContext(loginContext, getStorageService(), httpRequest.getSession()
206 .getServletContext(), httpRequest, httpResponse);
208 String authnEngineUrl = HttpServletHelper.getContextRelativeUrl(httpRequest, authenticationManagerPath)
210 log.debug("Redirecting user to authentication engine at {}", authnEngineUrl);
211 httpResponse.sendRedirect(authnEngineUrl);
212 } catch (MarshallingException e) {
213 log.error("Unable to marshall authentication request context");
214 throw new ProfileException("Unable to marshall authentication request context", e);
215 } catch (IOException ex) {
216 log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
217 throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
222 * Creates a response to the {@link AuthnRequest} and sends the user, with response in tow, back to the relying
223 * party after they've been authenticated.
225 * @param loginContext login context for this request
226 * @param inTransport inbound message transport
227 * @param outTransport outbound message transport
229 * @throws ProfileException thrown if the response can not be created and sent back to the relying party
231 protected void completeAuthenticationRequest(Saml2LoginContext loginContext, HTTPInTransport inTransport,
232 HTTPOutTransport outTransport) throws ProfileException {
233 SSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
235 Response samlResponse;
237 checkSamlVersion(requestContext);
238 checkNameIDPolicy(requestContext);
240 if (loginContext.getAuthenticationFailure() != null) {
241 if (loginContext.getAuthenticationFailure() instanceof PassiveAuthenticationException) {
242 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.NO_PASSIVE_URI,
245 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI,
248 throw new ProfileException("Authentication failure", loginContext.getAuthenticationFailure());
251 if (requestContext.getSubjectNameIdentifier() != null) {
252 log.debug("Authentication request contained a subject with a name identifier, resolving principal from NameID");
253 resolvePrincipal(requestContext);
254 String requestedPrincipalName = requestContext.getPrincipalName();
255 if (!DatatypeHelper.safeEquals(loginContext.getPrincipalName(), requestedPrincipalName)) {
257 "Authentication request identified principal {} but authentication mechanism identified principal {}",
258 requestedPrincipalName, loginContext.getPrincipalName());
259 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI,
261 throw new ProfileException("User failed authentication");
265 resolveAttributes(requestContext);
267 ArrayList<Statement> statements = new ArrayList<Statement>();
268 statements.add(buildAuthnStatement(requestContext));
269 if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
270 AttributeStatement attributeStatement = buildAttributeStatement(requestContext);
271 if (attributeStatement != null) {
272 requestContext.setReleasedAttributes(requestContext.getAttributes().keySet());
273 statements.add(attributeStatement);
277 samlResponse = buildResponse(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:bearer", statements);
278 } catch (ProfileException e) {
279 samlResponse = buildErrorResponse(requestContext);
282 requestContext.setOutboundSAMLMessage(samlResponse);
283 requestContext.setOutboundSAMLMessageId(samlResponse.getID());
284 requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
285 encodeResponse(requestContext);
286 writeAuditLogEntry(requestContext);
290 * Decodes an incoming request and stores the information in a created request context.
292 * @param inTransport inbound transport
293 * @param outTransport outbound transport
294 * @param requestContext request context to which decoded information should be added
296 * @throws ProfileException thrown if the incoming message failed decoding
298 protected void decodeRequest(SSORequestContext requestContext, HTTPInTransport inTransport,
299 HTTPOutTransport outTransport) throws ProfileException {
300 if (log.isDebugEnabled()) {
301 log.debug("Decoding message with decoder binding '{}'", getInboundMessageDecoder(requestContext)
305 requestContext.setCommunicationProfileId(getProfileId());
307 requestContext.setMetadataProvider(getMetadataProvider());
308 requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
310 requestContext.setCommunicationProfileId(getProfileId());
311 requestContext.setInboundMessageTransport(inTransport);
312 requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
313 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
315 requestContext.setOutboundMessageTransport(outTransport);
316 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
319 SAMLMessageDecoder decoder = getInboundMessageDecoder(requestContext);
320 requestContext.setMessageDecoder(decoder);
321 decoder.decode(requestContext);
322 log.debug("Decoded request from relying party '{}'", requestContext.getInboundMessageIssuer());
324 if (!(requestContext.getInboundSAMLMessage() instanceof AuthnRequest)) {
325 log.warn("Incomming message was not a AuthnRequest, it was a '{}'", requestContext
326 .getInboundSAMLMessage().getClass().getName());
327 requestContext.setFailureStatus(buildStatus(StatusCode.REQUESTER_URI, null,
328 "Invalid SAML AuthnRequest message."));
329 throw new ProfileException("Invalid SAML AuthnRequest message.");
331 } catch (MessageDecodingException e) {
332 String msg = "Error decoding authentication request message";
334 throw new ProfileException(msg, e);
335 } catch (SecurityException e) {
336 String msg = "Message did not meet security requirements";
338 throw new ProfileException(msg, e);
343 * Checks to see, if present, if the affiliation associated with the SPNameQualifier given in the AuthnRequest
344 * NameIDPolicy lists the inbound message issuer as a member.
346 * @param requestContext current request context
348 * @throws ProfileException thrown if there the request is not a member of the affiliation or if there was a problem
349 * determining membership
351 protected void checkNameIDPolicy(SSORequestContext requestContext) throws ProfileException {
352 AuthnRequest request = requestContext.getInboundSAMLMessage();
354 NameIDPolicy nameIdPolcy = request.getNameIDPolicy();
355 if (nameIdPolcy == null) {
359 String spNameQualifier = DatatypeHelper.safeTrimOrNullString(nameIdPolcy.getSPNameQualifier());
360 if (spNameQualifier == null) {
364 log.debug("Checking if message issuer is a member of affiliation '{}'", spNameQualifier);
366 EntityDescriptor affiliation = getMetadataProvider().getEntityDescriptor(spNameQualifier);
367 if (affiliation != null) {
368 AffiliationDescriptor affiliationDescriptor = affiliation.getAffiliationDescriptor();
369 if (affiliationDescriptor != null && affiliationDescriptor.getMembers() != null) {
370 for (AffiliateMember member : affiliationDescriptor.getMembers()) {
371 if (DatatypeHelper.safeEquals(member.getID(), requestContext.getInboundMessageIssuer())) {
378 requestContext.setFailureStatus(buildStatus(StatusCode.REQUESTER_URI, StatusCode.INVALID_NAMEID_POLICY_URI,
379 "Invalid SPNameQualifier for this request"));
380 throw new ProfileException("Relying party '" + requestContext.getInboundMessageIssuer()
381 + "' is not a member of the affiliation " + spNameQualifier);
382 } catch (MetadataProviderException e) {
383 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Internal service error"));
384 log.error("Error looking up metadata for affiliation", e);
385 throw new ProfileException("Relying party '" + requestContext.getInboundMessageIssuer()
386 + "' is not a member of the affiliation " + spNameQualifier);
391 * Creates an authentication request context from the current environmental information.
393 * @param loginContext current login context
394 * @param in inbound transport
395 * @param out outbount transport
397 * @return created authentication request context
399 * @throws ProfileException thrown if there is a problem creating the context
401 protected SSORequestContext buildRequestContext(Saml2LoginContext loginContext, HTTPInTransport in,
402 HTTPOutTransport out) throws ProfileException {
403 SSORequestContext requestContext = new SSORequestContext();
404 requestContext.setCommunicationProfileId(getProfileId());
406 requestContext.setMessageDecoder(getInboundMessageDecoder(requestContext));
408 requestContext.setLoginContext(loginContext);
410 requestContext.setInboundMessageTransport(in);
411 requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
413 requestContext.setOutboundMessageTransport(out);
414 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
416 requestContext.setMetadataProvider(getMetadataProvider());
418 String relyingPartyId = loginContext.getRelyingPartyId();
419 requestContext.setPeerEntityId(relyingPartyId);
420 requestContext.setInboundMessageIssuer(relyingPartyId);
422 populateRequestContext(requestContext);
424 return requestContext;
428 protected void populateRelyingPartyInformation(BaseSAMLProfileRequestContext requestContext)
429 throws ProfileException {
430 super.populateRelyingPartyInformation(requestContext);
432 EntityDescriptor relyingPartyMetadata = requestContext.getPeerEntityMetadata();
433 if (relyingPartyMetadata != null) {
434 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
435 requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS));
440 protected void populateAssertingPartyInformation(BaseSAMLProfileRequestContext requestContext)
441 throws ProfileException {
442 super.populateAssertingPartyInformation(requestContext);
444 EntityDescriptor localEntityDescriptor = requestContext.getLocalEntityMetadata();
445 if (localEntityDescriptor != null) {
446 requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
447 requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
448 .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
453 * Populates the request context with information from the inbound SAML message.
455 * This method requires the the following request context properties to be populated: login context
457 * This methods populates the following request context properties: inbound saml message, relay state, inbound saml
458 * message ID, subject name identifier
460 * @param requestContext current request context
462 * @throws ProfileException thrown if the inbound SAML message or subject identifier is null
464 protected void populateSAMLMessageInformation(BaseSAMLProfileRequestContext requestContext) throws ProfileException {
465 SSORequestContext ssoRequestContext = (SSORequestContext) requestContext;
467 Saml2LoginContext loginContext = ssoRequestContext.getLoginContext();
468 requestContext.setRelayState(loginContext.getRelayState());
470 AuthnRequest authnRequest = deserializeRequest(loginContext.getAuthenticationRequest());
471 requestContext.setInboundMessage(authnRequest);
472 requestContext.setInboundSAMLMessage(authnRequest);
473 requestContext.setInboundSAMLMessageId(authnRequest.getID());
475 Subject authnSubject = authnRequest.getSubject();
476 if (authnSubject != null) {
477 requestContext.setSubjectNameIdentifier(authnSubject.getNameID());
479 } catch (UnmarshallingException e) {
480 log.error("Unable to unmarshall authentication request context");
481 ssoRequestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
482 "Error recovering request state"));
483 throw new ProfileException("Error recovering request state", e);
488 * Creates an authentication statement for the current request.
490 * @param requestContext current request context
492 * @return constructed authentication statement
494 protected AuthnStatement buildAuthnStatement(SSORequestContext requestContext) {
495 Saml2LoginContext loginContext = requestContext.getLoginContext();
497 AuthnContext authnContext = buildAuthnContext(requestContext);
499 AuthnStatement statement = authnStatementBuilder.buildObject();
500 statement.setAuthnContext(authnContext);
501 statement.setAuthnInstant(loginContext.getAuthenticationInstant());
503 Session session = getUserSession(requestContext.getInboundMessageTransport());
504 if (session != null) {
505 statement.setSessionIndex(session.getSessionID());
508 long maxSPSessionLifetime = requestContext.getProfileConfiguration().getMaximumSPSessionLifetime();
509 if (maxSPSessionLifetime > 0) {
510 DateTime lifetime = new DateTime(DateTimeZone.UTC).plus(maxSPSessionLifetime);
511 log.debug("Explicitly setting SP session expiration time to '{}'", lifetime.toString());
512 statement.setSessionNotOnOrAfter(lifetime);
515 statement.setSubjectLocality(buildSubjectLocality(requestContext));
521 * Creates an {@link AuthnContext} for a successful authentication request.
523 * @param requestContext current request
525 * @return the built authn context
527 protected AuthnContext buildAuthnContext(SSORequestContext requestContext) {
528 AuthnContext authnContext = authnContextBuilder.buildObject();
530 Saml2LoginContext loginContext = requestContext.getLoginContext();
531 AuthnRequest authnRequest = requestContext.getInboundSAMLMessage();
532 RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
533 if (requestedAuthnContext != null) {
534 if (requestedAuthnContext.getAuthnContextClassRefs() != null) {
535 for (AuthnContextClassRef classRef : requestedAuthnContext.getAuthnContextClassRefs()) {
536 if (DatatypeHelper.safeEquals(classRef.getAuthnContextClassRef(),
537 loginContext.getAuthenticationMethod())) {
538 AuthnContextClassRef ref = authnContextClassRefBuilder.buildObject();
539 ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
540 authnContext.setAuthnContextClassRef(ref);
543 } else if (requestedAuthnContext.getAuthnContextDeclRefs() != null) {
544 for (AuthnContextDeclRef declRef : requestedAuthnContext.getAuthnContextDeclRefs()) {
545 if (DatatypeHelper.safeEquals(declRef.getAuthnContextDeclRef(),
546 loginContext.getAuthenticationMethod())) {
547 AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
548 ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
549 authnContext.setAuthnContextDeclRef(ref);
555 if (authnContext.getAuthnContextClassRef() == null || authnContext.getAuthnContextDeclRef() == null) {
556 AuthnContextClassRef ref = authnContextClassRefBuilder.buildObject();
557 ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
558 authnContext.setAuthnContextClassRef(ref);
565 * Constructs the subject locality for the authentication statement.
567 * @param requestContext curent request context
569 * @return subject locality for the authentication statement
571 protected SubjectLocality buildSubjectLocality(SSORequestContext requestContext) {
572 HTTPInTransport transport = (HTTPInTransport) requestContext.getInboundMessageTransport();
573 SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
574 subjectLocality.setAddress(transport.getPeerAddress());
576 return subjectLocality;
580 protected String getRequiredNameIDFormat(BaseSAMLProfileRequestContext requestContext) {
581 String requiredNameFormat = null;
582 AuthnRequest authnRequest = (AuthnRequest) requestContext.getInboundSAMLMessage();
583 NameIDPolicy nameIdPolicy = authnRequest.getNameIDPolicy();
584 if (nameIdPolicy != null) {
585 requiredNameFormat = DatatypeHelper.safeTrimOrNullString(nameIdPolicy.getFormat());
586 // Check for unspec'd or encryption formats, which aren't relevant for this section of code.
587 if (requiredNameFormat != null
588 && (NameID.ENCRYPTED.equals(requiredNameFormat) || NameID.UNSPECIFIED.equals(requiredNameFormat))) {
589 requiredNameFormat = null;
593 return requiredNameFormat;
597 protected NameID buildNameId(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
598 NameID nameId = super.buildNameId(requestContext);
599 if (nameId != null) {
600 AuthnRequest authnRequest = (AuthnRequest) requestContext.getInboundSAMLMessage();
601 NameIDPolicy nameIdPolicy = authnRequest.getNameIDPolicy();
602 if (nameIdPolicy != null) {
603 String spNameQualifier = DatatypeHelper.safeTrimOrNullString(nameIdPolicy.getSPNameQualifier());
604 if (spNameQualifier != null) {
605 nameId.setSPNameQualifier(spNameQualifier);
607 nameId.setSPNameQualifier(requestContext.getInboundMessageIssuer());
616 * Selects the appropriate endpoint for the relying party and stores it in the request context.
618 * @param requestContext current request context
620 * @return Endpoint selected from the information provided in the request context
622 protected Endpoint selectEndpoint(BaseSAMLProfileRequestContext requestContext) {
623 AuthnRequest authnRequest = ((SSORequestContext) requestContext).getInboundSAMLMessage();
625 Endpoint endpoint = null;
626 if (requestContext.getRelyingPartyConfiguration().getRelyingPartyId() == SAMLMDRelyingPartyConfigurationManager.ANONYMOUS_RP_NAME) {
627 if (authnRequest.getAssertionConsumerServiceURL() != null) {
628 endpoint = endpointBuilder.buildObject();
629 endpoint.setLocation(authnRequest.getAssertionConsumerServiceURL());
630 if (authnRequest.getProtocolBinding() != null) {
631 endpoint.setBinding(authnRequest.getProtocolBinding());
633 endpoint.setBinding(getSupportedOutboundBindings().get(0));
636 "Generating endpoint for anonymous relying party self-identified as '{}', ACS url '{}' and binding '{}'",
637 new Object[] { requestContext.getInboundMessageIssuer(), endpoint.getLocation(),
638 endpoint.getBinding(), });
640 log.warn("Unable to generate endpoint for anonymous party. No ACS url provided.");
643 AuthnResponseEndpointSelector endpointSelector = new AuthnResponseEndpointSelector();
644 endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
645 endpointSelector.setMetadataProvider(getMetadataProvider());
646 endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
647 endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
648 endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
649 endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
650 endpoint = endpointSelector.selectEndpoint();
657 * Deserailizes an authentication request from a string.
659 * @param request request to deserialize
661 * @return the request XMLObject
663 * @throws UnmarshallingException thrown if the request can no be deserialized and unmarshalled
665 protected AuthnRequest deserializeRequest(String request) throws UnmarshallingException {
667 Element requestElem = getParserPool().parse(new StringReader(request)).getDocumentElement();
668 Unmarshaller unmarshaller = Configuration.getUnmarshallerFactory().getUnmarshaller(requestElem);
669 return (AuthnRequest) unmarshaller.unmarshall(requestElem);
670 } catch (Exception e) {
671 throw new UnmarshallingException("Unable to read serialized authentication request");
675 /** Represents the internal state of a SAML 2.0 SSO Request while it's being processed by the IdP. */
676 protected class SSORequestContext extends BaseSAML2ProfileRequestContext<AuthnRequest, Response, SSOConfiguration> {
678 /** Current login context. */
679 private Saml2LoginContext loginContext;
682 * Gets the current login context.
684 * @return current login context
686 public Saml2LoginContext getLoginContext() {
691 * Sets the current login context.
693 * @param context current login context
695 public void setLoginContext(Saml2LoginContext context) {
696 loginContext = context;