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.util.ArrayList;
20 import java.util.Collection;
21 import java.util.List;
24 import javax.servlet.ServletRequest;
25 import javax.servlet.ServletResponse;
27 import org.apache.log4j.Logger;
28 import org.joda.time.DateTime;
29 import org.opensaml.common.SAMLObjectBuilder;
30 import org.opensaml.common.SAMLVersion;
31 import org.opensaml.common.impl.SAMLObjectContentReference;
32 import org.opensaml.log.Level;
33 import org.opensaml.saml2.core.Assertion;
34 import org.opensaml.saml2.core.AttributeQuery;
35 import org.opensaml.saml2.core.AttributeStatement;
36 import org.opensaml.saml2.core.Audience;
37 import org.opensaml.saml2.core.AudienceRestriction;
38 import org.opensaml.saml2.core.AuthnRequest;
39 import org.opensaml.saml2.core.Conditions;
40 import org.opensaml.saml2.core.Issuer;
41 import org.opensaml.saml2.core.NameID;
42 import org.opensaml.saml2.core.ProxyRestriction;
43 import org.opensaml.saml2.core.RequestAbstractType;
44 import org.opensaml.saml2.core.Response;
45 import org.opensaml.saml2.core.Statement;
46 import org.opensaml.saml2.core.Status;
47 import org.opensaml.saml2.core.StatusCode;
48 import org.opensaml.saml2.core.StatusMessage;
49 import org.opensaml.saml2.core.StatusResponseType;
50 import org.opensaml.saml2.core.Subject;
51 import org.opensaml.saml2.core.SubjectConfirmation;
52 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
53 import org.opensaml.saml2.metadata.AuthnAuthorityDescriptor;
54 import org.opensaml.saml2.metadata.NameIDFormat;
55 import org.opensaml.saml2.metadata.PDPDescriptor;
56 import org.opensaml.saml2.metadata.RoleDescriptor;
57 import org.opensaml.saml2.metadata.SPSSODescriptor;
58 import org.opensaml.saml2.metadata.SSODescriptor;
59 import org.opensaml.xml.XMLObjectBuilder;
60 import org.opensaml.xml.security.credential.Credential;
61 import org.opensaml.xml.signature.Signature;
62 import org.opensaml.xml.signature.Signer;
63 import org.opensaml.xml.util.DatatypeHelper;
65 import edu.internet2.middleware.shibboleth.common.attribute.AttributeRequestException;
66 import edu.internet2.middleware.shibboleth.common.attribute.BaseAttribute;
67 import edu.internet2.middleware.shibboleth.common.attribute.encoding.AttributeEncoder;
68 import edu.internet2.middleware.shibboleth.common.attribute.encoding.AttributeEncodingException;
69 import edu.internet2.middleware.shibboleth.common.attribute.encoding.SAML2NameIDAttributeEncoder;
70 import edu.internet2.middleware.shibboleth.common.attribute.provider.SAML2AttributeAuthority;
71 import edu.internet2.middleware.shibboleth.common.attribute.provider.ShibbolethSAMLAttributeRequestContext;
72 import edu.internet2.middleware.shibboleth.common.log.AuditLogEntry;
73 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
74 import edu.internet2.middleware.shibboleth.common.profile.ProfileRequest;
75 import edu.internet2.middleware.shibboleth.common.profile.ProfileResponse;
76 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.AbstractSAML2ProfileConfiguration;
77 import edu.internet2.middleware.shibboleth.idp.profile.AbstractSAMLProfileHandler;
78 import edu.internet2.middleware.shibboleth.idp.session.ServiceInformation;
79 import edu.internet2.middleware.shibboleth.idp.session.Session;
81 /** Common implementation details for profile handlers. */
82 public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHandler {
84 /** SAML Version for this profile handler. */
85 public static final SAMLVersion SAML_VERSION = SAMLVersion.VERSION_20;
88 private Logger log = Logger.getLogger(AbstractSAML2ProfileHandler.class);
90 /** For building response. */
91 private SAMLObjectBuilder<Response> responseBuilder;
93 /** For building status. */
94 private SAMLObjectBuilder<Status> statusBuilder;
96 /** For building statuscode. */
97 private SAMLObjectBuilder<StatusCode> statusCodeBuilder;
99 /** For building StatusMessages. */
100 private SAMLObjectBuilder<StatusMessage> statusMessageBuilder;
102 /** For building assertion. */
103 private SAMLObjectBuilder<Assertion> assertionBuilder;
105 /** For building issuer. */
106 private SAMLObjectBuilder<Issuer> issuerBuilder;
108 /** For building subject. */
109 private SAMLObjectBuilder<Subject> subjectBuilder;
111 /** For builder subject confirmation. */
112 private SAMLObjectBuilder<SubjectConfirmation> subjectConfirmationBuilder;
114 /** For building conditions. */
115 private SAMLObjectBuilder<Conditions> conditionsBuilder;
117 /** For building audience restriction. */
118 private SAMLObjectBuilder<AudienceRestriction> audienceRestrictionBuilder;
120 /** For building proxy retrictions. */
121 private SAMLObjectBuilder<ProxyRestriction> proxyRestrictionBuilder;
123 /** For building audience. */
124 private SAMLObjectBuilder<Audience> audienceBuilder;
126 /** For building signature. */
127 private XMLObjectBuilder<Signature> signatureBuilder;
130 @SuppressWarnings("unchecked")
131 protected AbstractSAML2ProfileHandler() {
134 responseBuilder = (SAMLObjectBuilder<Response>) getBuilderFactory().getBuilder(Response.DEFAULT_ELEMENT_NAME);
135 statusBuilder = (SAMLObjectBuilder<Status>) getBuilderFactory().getBuilder(Status.DEFAULT_ELEMENT_NAME);
136 statusCodeBuilder = (SAMLObjectBuilder<StatusCode>) getBuilderFactory().getBuilder(
137 StatusCode.DEFAULT_ELEMENT_NAME);
138 statusMessageBuilder = (SAMLObjectBuilder<StatusMessage>) getBuilderFactory().getBuilder(
139 StatusMessage.DEFAULT_ELEMENT_NAME);
140 issuerBuilder = (SAMLObjectBuilder<Issuer>) getBuilderFactory().getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
141 assertionBuilder = (SAMLObjectBuilder<Assertion>) getBuilderFactory()
142 .getBuilder(Assertion.DEFAULT_ELEMENT_NAME);
143 subjectBuilder = (SAMLObjectBuilder<Subject>) getBuilderFactory().getBuilder(Subject.DEFAULT_ELEMENT_NAME);
144 subjectConfirmationBuilder = (SAMLObjectBuilder<SubjectConfirmation>) getBuilderFactory().getBuilder(
145 SubjectConfirmation.DEFAULT_ELEMENT_NAME);
146 conditionsBuilder = (SAMLObjectBuilder<Conditions>) getBuilderFactory().getBuilder(
147 Conditions.DEFAULT_ELEMENT_NAME);
148 audienceRestrictionBuilder = (SAMLObjectBuilder<AudienceRestriction>) getBuilderFactory().getBuilder(
149 AudienceRestriction.DEFAULT_ELEMENT_NAME);
150 proxyRestrictionBuilder = (SAMLObjectBuilder<ProxyRestriction>) getBuilderFactory().getBuilder(
151 ProxyRestriction.DEFAULT_ELEMENT_NAME);
152 audienceBuilder = (SAMLObjectBuilder<Audience>) getBuilderFactory().getBuilder(Audience.DEFAULT_ELEMENT_NAME);
153 signatureBuilder = (XMLObjectBuilder<Signature>) getBuilderFactory().getBuilder(Signature.DEFAULT_ELEMENT_NAME);
157 * Checks that the SAML major version for a request is 2.
159 * @param requestContext current request context containing the SAML message
161 * @throws ProfileException thrown if the major version of the SAML request is not 2
163 protected void checkSamlVersion(SAML2ProfileRequestContext requestContext) throws ProfileException {
164 SAMLVersion version = requestContext.getSamlRequest().getVersion();
165 if (version.getMajorVersion() < 2) {
166 requestContext.setFailureStatus(buildStatus(StatusCode.VERSION_MISMATCH_URI,
167 StatusCode.REQUEST_VERSION_TOO_LOW_URI, null));
168 throw new ProfileException("SAML request version too low");
169 } else if (version.getMajorVersion() > 2) {
170 requestContext.setFailureStatus(buildStatus(StatusCode.VERSION_MISMATCH_URI,
171 StatusCode.REQUEST_VERSION_TOO_HIGH_URI, null));
172 throw new ProfileException("SAML request version too high");
177 * Builds a response to the attribute query within the request context.
179 * @param requestContext current request context
180 * @param assertionSubject subject of the assertion within the response
181 * @param statements the statements to include in the response
183 * @return the built response
185 * @throws ProfileException thrown if there is a problem creating the SAML response
187 protected Response buildResponse(SAML2ProfileRequestContext requestContext, Subject assertionSubject,
188 List<Statement> statements) throws ProfileException {
190 DateTime issueInstant = new DateTime();
192 // create the assertion and add the attribute statement
193 Assertion assertion = buildAssertion(requestContext, issueInstant);
194 assertion.setSubject(assertionSubject);
195 if (statements != null) {
196 assertion.getStatements().addAll(statements);
199 // create the SAML response and add the assertion
200 Response samlResponse = responseBuilder.buildObject();
201 samlResponse.setIssueInstant(issueInstant);
202 populateStatusResponse(requestContext, samlResponse);
204 samlResponse.getAssertions().add(assertion);
206 // sign the assertion if it should be signed
207 signAssertion(requestContext, assertion);
209 Status status = buildStatus(StatusCode.SUCCESS_URI, null, null);
210 samlResponse.setStatus(status);
216 * Builds a basic assertion with its id, issue instant, SAML version, issuer, subject, and conditions populated.
218 * @param requestContext current request context
219 * @param issueInstant time to use as assertion issue instant
221 * @return the built assertion
223 protected Assertion buildAssertion(SAML2ProfileRequestContext requestContext, DateTime issueInstant) {
224 Assertion assertion = assertionBuilder.buildObject();
225 assertion.setID(getIdGenerator().generateIdentifier());
226 assertion.setIssueInstant(issueInstant);
227 assertion.setVersion(SAMLVersion.VERSION_20);
228 assertion.setIssuer(buildEntityIssuer(requestContext));
230 Conditions conditions = buildConditions(requestContext, issueInstant);
231 assertion.setConditions(conditions);
237 * Creates an {@link Issuer} populated with information about the relying party.
239 * @param requestContext current request context
241 * @return the built issuer
243 protected Issuer buildEntityIssuer(SAML2ProfileRequestContext requestContext) {
244 Issuer issuer = issuerBuilder.buildObject();
245 issuer.setFormat(Issuer.ENTITY);
246 issuer.setValue(requestContext.getAssertingPartyId());
252 * Builds a SAML assertion condition set. The following fields are set; not before, not on or after, audience
253 * restrictions, and proxy restrictions.
255 * @param requestContext current request context
256 * @param issueInstant timestamp the assertion was created
258 * @return constructed conditions
260 protected Conditions buildConditions(SAML2ProfileRequestContext requestContext, DateTime issueInstant) {
261 AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
263 Conditions conditions = conditionsBuilder.buildObject();
264 conditions.setNotBefore(issueInstant);
265 conditions.setNotOnOrAfter(issueInstant.plus(profileConfig.getAssertionLifetime()));
267 Collection<String> audiences;
269 // add audience restrictions
270 audiences = profileConfig.getAssertionAudiences();
271 if (audiences != null && audiences.size() > 0) {
272 AudienceRestriction audienceRestriction = audienceRestrictionBuilder.buildObject();
273 for (String audienceUri : audiences) {
274 Audience audience = audienceBuilder.buildObject();
275 audience.setAudienceURI(audienceUri);
276 audienceRestriction.getAudiences().add(audience);
278 conditions.getAudienceRestrictions().add(audienceRestriction);
281 // add proxy restrictions
282 audiences = profileConfig.getProxyAudiences();
283 if (audiences != null && audiences.size() > 0) {
284 ProxyRestriction proxyRestriction = proxyRestrictionBuilder.buildObject();
286 for (String audienceUri : audiences) {
287 audience = audienceBuilder.buildObject();
288 audience.setAudienceURI(audienceUri);
289 proxyRestriction.getAudiences().add(audience);
292 proxyRestriction.setProxyCount(profileConfig.getProxyCount());
293 conditions.getConditions().add(proxyRestriction);
300 * Populates the response's id, in response to, issue instant, version, and issuer properties.
302 * @param requestContext current request context
303 * @param response the response to populate
305 protected void populateStatusResponse(SAML2ProfileRequestContext requestContext, StatusResponseType response) {
306 response.setID(getIdGenerator().generateIdentifier());
307 if (requestContext.getSamlRequest() != null) {
308 response.setInResponseTo(requestContext.getSamlRequest().getID());
310 response.setVersion(SAMLVersion.VERSION_20);
311 response.setIssuer(buildEntityIssuer(requestContext));
315 * Executes a query for attributes and builds a SAML attribute statement from the results.
317 * @param requestContext current request context
319 * @return attribute statement resulting from the query
321 * @throws ProfileException thrown if there is a problem making the query
323 protected AttributeStatement buildAttributeStatement(SAML2ProfileRequestContext requestContext)
324 throws ProfileException {
326 if (log.isDebugEnabled()) {
327 log.debug("Creating attribute statement in response to SAML request "
328 + requestContext.getSamlRequest().getID() + " from relying party "
329 + requestContext.getRelyingPartyId());
332 AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
333 SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
336 if (log.isDebugEnabled()) {
337 log.debug("Resolving attributes for principal " + requestContext.getPrincipalName()
338 + " of SAML request " + requestContext.getSamlRequest().getID() + " from relying party "
339 + requestContext.getRelyingPartyId());
341 Map<String, BaseAttribute> principalAttributes = attributeAuthority
342 .getAttributes(buildAttributeRequestContext(requestContext));
344 requestContext.setPrincipalAttributes(principalAttributes);
346 if (requestContext.getSamlRequest() instanceof AttributeQuery) {
347 return attributeAuthority.buildAttributeStatement((AttributeQuery) requestContext.getSamlRequest(),
348 principalAttributes.values());
350 return attributeAuthority.buildAttributeStatement(null, principalAttributes.values());
352 } catch (AttributeRequestException e) {
353 log.error("Error resolving attributes for SAML request " + requestContext.getSamlRequest().getID()
354 + " from relying party " + requestContext.getRelyingPartyId(), e);
355 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error resolving attributes"));
356 throw new ProfileException("Error resolving attributes for SAML request "
357 + requestContext.getSamlRequest().getID() + " from relying party "
358 + requestContext.getRelyingPartyId(), e);
363 * Resolves the principal name of the subject of the request.
365 * @param requestContext current request context
367 * @throws ProfileException thrown if the principal name can not be resolved
369 protected void resolvePrincipal(SAML2ProfileRequestContext requestContext) throws ProfileException {
370 AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
371 if (profileConfiguration == null) {
372 log.error("Unable to resolve principal, no SAML 2 profile configuration for relying party "
373 + requestContext.getRelyingPartyId());
374 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
375 "Error resolving principal"));
376 throw new ProfileException(
377 "Unable to resolve principal, no SAML 2 profile configuration for relying party "
378 + requestContext.getRelyingPartyId());
380 SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
382 if (log.isDebugEnabled()) {
383 log.debug("Resolving principal name for subject of SAML request " + requestContext.getSamlRequest().getID()
384 + " from relying party " + requestContext.getRelyingPartyId());
388 String principal = attributeAuthority.getPrincipal(buildAttributeRequestContext(requestContext));
389 requestContext.setPrincipalName(principal);
390 } catch (AttributeRequestException e) {
391 log.error("Error resolving attributes for SAML request " + requestContext.getSamlRequest().getID()
392 + " from relying party " + requestContext.getRelyingPartyId(), e);
393 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.UNKNOWN_PRINCIPAL_URI,
394 "Error resolving principal"));
395 throw new ProfileException("Error resolving attributes for SAML request "
396 + requestContext.getSamlRequest().getID() + " from relying party "
397 + requestContext.getRelyingPartyId(), e);
402 * Creates an attribute query context from the current profile request context.
404 * @param requestContext current profile request
406 * @return created query context
408 protected ShibbolethSAMLAttributeRequestContext<NameID, AttributeQuery> buildAttributeRequestContext(
409 SAML2ProfileRequestContext requestContext) {
411 ShibbolethSAMLAttributeRequestContext<NameID, AttributeQuery> queryContext;
413 queryContext = new ShibbolethSAMLAttributeRequestContext<NameID, AttributeQuery>(getMetadataProvider(),
414 requestContext.getRelyingPartyConfiguration(), (AttributeQuery) requestContext.getSamlRequest());
415 queryContext.setAttributeRequester(requestContext.getAssertingPartyId());
416 queryContext.setPrincipalName(requestContext.getPrincipalName());
417 queryContext.setProfileConfiguration(requestContext.getProfileConfiguration());
418 queryContext.setRequest(requestContext.getProfileRequest());
420 Session userSession = getSessionManager().getSession(getUserSessionId(requestContext.getProfileRequest()));
421 if (userSession != null) {
422 queryContext.setUserSession(userSession);
423 ServiceInformation serviceInfo = userSession.getServicesInformation().get(
424 requestContext.getRelyingPartyId());
425 if (serviceInfo != null) {
426 String principalAuthenticationMethod = serviceInfo.getAuthenticationMethod().getAuthenticationMethod();
428 requestContext.setPrincipalAuthenticationMethod(principalAuthenticationMethod);
429 queryContext.setPrincipalAuthenticationMethod(principalAuthenticationMethod);
437 * Signs the given assertion if either the current profile configuration or the relying party configuration contains
438 * signing credentials.
440 * @param requestContext current request context
441 * @param assertion assertion to sign
443 * @throws ProfileException thrown if the metadata can not be located for the relying party or, if signing is
444 * required, if a signing credential is not configured
446 protected void signAssertion(SAML2ProfileRequestContext requestContext, Assertion assertion)
447 throws ProfileException {
448 if (log.isDebugEnabled()) {
449 log.debug("Determining if SAML assertion to relying party " + requestContext.getRelyingPartyId()
450 + " should be signed");
453 boolean signAssertion = false;
455 AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
457 if (requestContext.getRelyingPartyRoleMetadata() instanceof SPSSODescriptor) {
458 SPSSODescriptor ssoDescriptor = (SPSSODescriptor) requestContext.getRelyingPartyRoleMetadata();
459 if (ssoDescriptor.getWantAssertionsSigned() != null) {
460 signAssertion = ssoDescriptor.getWantAssertionsSigned().booleanValue();
461 if (log.isDebugEnabled()) {
462 log.debug("Entity metadata for relying party " + requestContext.getRelyingPartyId()
463 + " indicates to sign assertions: " + signAssertion);
466 } else if (profileConfig.getSignAssertions()) {
467 signAssertion = true;
468 log.debug("IdP relying party configuration "
469 + requestContext.getRelyingPartyConfiguration().getRelyingPartyId()
470 + " indicates to sign assertions: " + signAssertion);
473 if (!signAssertion) {
477 if (log.isDebugEnabled()) {
478 log.debug("Determining signing credntial for assertion to relying party "
479 + requestContext.getRelyingPartyId());
481 Credential signatureCredential = profileConfig.getSigningCredential();
482 if (signatureCredential == null) {
483 signatureCredential = requestContext.getRelyingPartyConfiguration().getDefaultSigningCredential();
486 if (signatureCredential == null) {
487 throw new ProfileException("No signing credential is specified for relying party configuration "
488 + requestContext.getRelyingPartyConfiguration().getProviderId()
489 + " or it's SAML2 attribute query profile configuration");
492 if (log.isDebugEnabled()) {
493 log.debug("Signing assertion to relying party " + requestContext.getRelyingPartyId());
495 SAMLObjectContentReference contentRef = new SAMLObjectContentReference(assertion);
496 Signature signature = signatureBuilder.buildObject(Signature.DEFAULT_ELEMENT_NAME);
497 signature.getContentReferences().add(contentRef);
498 assertion.setSignature(signature);
500 Signer.signObject(signature);
504 * Build a status message, with an optional second-level failure message.
506 * @param topLevelCode The top-level status code. Should be from saml-core-2.0-os, sec. 3.2.2.2
507 * @param secondLevelCode An optional second-level failure code. Should be from saml-core-2.0-is, sec 3.2.2.2. If
508 * null, no second-level Status element will be set.
509 * @param failureMessage An optional second-level failure message
511 * @return a Status object.
513 protected Status buildStatus(String topLevelCode, String secondLevelCode, String failureMessage) {
514 Status status = statusBuilder.buildObject();
516 StatusCode statusCode = statusCodeBuilder.buildObject();
517 statusCode.setValue(DatatypeHelper.safeTrimOrNullString(topLevelCode));
518 status.setStatusCode(statusCode);
520 if (secondLevelCode != null) {
521 StatusCode secondLevelStatusCode = statusCodeBuilder.buildObject();
522 secondLevelStatusCode.setValue(DatatypeHelper.safeTrimOrNullString(secondLevelCode));
523 statusCode.setStatusCode(secondLevelStatusCode);
526 if (failureMessage != null) {
527 StatusMessage msg = statusMessageBuilder.buildObject();
528 msg.setMessage(failureMessage);
529 status.setStatusMessage(msg);
536 * Builds the SAML subject for the user for the service provider.
538 * @param requestContext current request context
539 * @param confirmationMethod subject confirmation method used for the subject
541 * @return SAML subject for the user for the service provider
543 * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
544 * name ID attribute or because there are no supported name formats
546 protected Subject buildSubject(SAML2ProfileRequestContext requestContext, String confirmationMethod)
547 throws ProfileException {
548 NameID nameID = buildNameId(requestContext);
549 requestContext.setSubjectNameID(nameID);
550 // TODO handle encryption
552 SubjectConfirmation subjectConfirmation = subjectConfirmationBuilder.buildObject();
553 subjectConfirmation.setMethod(confirmationMethod);
555 Subject subject = subjectBuilder.buildObject();
556 subject.setNameID(nameID);
557 subject.getSubjectConfirmations().add(subjectConfirmation);
563 * Builds a NameID appropriate for this request. NameIDs are built by inspecting the SAML request and metadata,
564 * picking a name format that was requested by the relying party or is mutually supported by both the relying party
565 * and asserting party as described in their metadata entries. Once a set of supported name formats is determined
566 * the principals attributes are inspected for an attribute supported an attribute encoder whose category is one of
567 * the supported name formats.
569 * @param requestContext current request context
571 * @return the NameID appropriate for this request
573 * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
574 * name ID attribute or because there are no supported name formats
576 protected NameID buildNameId(SAML2ProfileRequestContext requestContext) throws ProfileException {
577 if (log.isDebugEnabled()) {
578 log.debug("Building assertion NameID for principal/relying party:" + requestContext.getPrincipalName()
579 + "/" + requestContext.getRelyingPartyId());
581 Map<String, BaseAttribute> principalAttributes = requestContext.getPrincipalAttributes();
582 List<String> supportedNameFormats = getNameFormats(requestContext);
584 if (log.isDebugEnabled()) {
585 log.debug("Supported NameID formats: " + supportedNameFormats);
588 if (principalAttributes == null || supportedNameFormats == null) {
589 log.error("No attributes for principal " + requestContext.getPrincipalName()
590 + " support constructions of NameID");
591 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.INVALID_NAMEID_POLICY_URI,
592 "Unable to construct NameID"));
593 throw new ProfileException("No principal attributes support NameID construction");
597 SAML2NameIDAttributeEncoder nameIdEncoder;
598 for (BaseAttribute<?> attribute : principalAttributes.values()) {
599 for (AttributeEncoder encoder : attribute.getEncoders()) {
600 if (encoder instanceof SAML2NameIDAttributeEncoder) {
601 nameIdEncoder = (SAML2NameIDAttributeEncoder) encoder;
602 if (supportedNameFormats.contains(nameIdEncoder.getNameFormat())) {
603 if (log.isDebugEnabled()) {
604 log.debug("Using attribute " + attribute.getId() + " suppoting NameID format "
605 + nameIdEncoder.getNameFormat() + " to create the NameID for principal "
606 + requestContext.getPrincipalName());
608 return nameIdEncoder.encode(attribute);
613 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Unable to construct NameID"));
614 throw new ProfileException("No principal attribute supported encoding into the a supported name ID format.");
615 } catch (AttributeEncodingException e) {
616 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Unable to construct NameID"));
617 throw new ProfileException("Unable to encode NameID attribute", e);
622 * Gets the NameID format to use when creating NameIDs for the relying party.
624 * @param requestContext current request context
626 * @return list of nameID formats that may be used with the relying party
628 * @throws ProfileException thrown if there is a problem determing the NameID format to use
630 protected List<String> getNameFormats(SAML2ProfileRequestContext requestContext) throws ProfileException {
631 ArrayList<String> nameFormats = new ArrayList<String>();
633 List<String> assertingPartySupportedFormats = getEntitySupportedFormats(requestContext
634 .getAssertingPartyRoleMetadata());
636 String nameFormat = null;
637 if (requestContext.getSamlRequest() instanceof AuthnRequest) {
638 AuthnRequest authnRequest = (AuthnRequest) requestContext.getSamlRequest();
639 if (authnRequest.getNameIDPolicy() != null) {
640 nameFormat = authnRequest.getNameIDPolicy().getFormat();
641 if (assertingPartySupportedFormats.contains(nameFormat)) {
642 nameFormats.add(nameFormat);
644 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI,
645 StatusCode.INVALID_NAMEID_POLICY_URI, "Format not supported: " + nameFormat));
646 throw new ProfileException("NameID format required by relying party is not supported");
651 if (nameFormats.isEmpty()) {
652 List<String> relyingPartySupportedFormats = getEntitySupportedFormats(requestContext
653 .getRelyingPartyRoleMetadata());
655 assertingPartySupportedFormats.retainAll(relyingPartySupportedFormats);
656 nameFormats.addAll(assertingPartySupportedFormats);
658 if (nameFormats.isEmpty()) {
659 nameFormats.add("urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified");
666 * Gets the list of NameID formats supported for a given role.
668 * @param role the role to get the list of supported NameID formats
670 * @return list of supported NameID formats
672 protected List<String> getEntitySupportedFormats(RoleDescriptor role) {
673 List<NameIDFormat> nameIDFormats = null;
675 if (role instanceof SSODescriptor) {
676 nameIDFormats = ((SSODescriptor) role).getNameIDFormats();
677 } else if (role instanceof AuthnAuthorityDescriptor) {
678 nameIDFormats = ((AuthnAuthorityDescriptor) role).getNameIDFormats();
679 } else if (role instanceof PDPDescriptor) {
680 nameIDFormats = ((PDPDescriptor) role).getNameIDFormats();
681 } else if (role instanceof AttributeAuthorityDescriptor) {
682 nameIDFormats = ((AttributeAuthorityDescriptor) role).getNameIDFormats();
685 ArrayList<String> supportedFormats = new ArrayList<String>();
686 if (nameIDFormats != null) {
687 for (NameIDFormat format : nameIDFormats) {
688 supportedFormats.add(format.getFormat());
692 return supportedFormats;
696 * Constructs an SAML response message carrying a request error.
698 * @param requestContext current request context
700 * @return the constructed error response
702 protected Response buildErrorResponse(SAML2ProfileRequestContext requestContext) {
703 Response samlResponse = responseBuilder.buildObject();
704 samlResponse.setIssueInstant(new DateTime());
705 populateStatusResponse(requestContext, samlResponse);
707 samlResponse.setStatus(requestContext.getFailureStatus());
713 * Writes an aduit log entry indicating the successful response to the attribute request.
715 * @param context current request context
717 protected void writeAuditLogEntry(SAML2ProfileRequestContext context) {
718 AuditLogEntry auditLogEntry = new AuditLogEntry();
719 auditLogEntry.setMessageProfile(getProfileId());
720 auditLogEntry.setPrincipalAuthenticationMethod(context.getPrincipalAuthenticationMethod());
721 auditLogEntry.setPrincipalName(context.getPrincipalName());
722 auditLogEntry.setAssertingPartyId(context.getAssertingPartyId());
723 auditLogEntry.setRelyingPartyId(context.getRelyingPartyId());
724 auditLogEntry.setRequestBinding(context.getMessageDecoder().getBindingURI());
725 auditLogEntry.setRequestId(context.getSamlRequest().getID());
726 auditLogEntry.setResponseBinding(context.getMessageEncoder().getBindingURI());
727 auditLogEntry.setResponseId(context.getSamlResponse().getID());
728 getAduitLog().log(Level.CRITICAL, auditLogEntry);
732 * Contextual object used to accumlate information as profile requests are being processed.
734 * @param <RequestType> type of SAML 2 request
735 * @param <ResponseType> type of SAML 2 response
736 * @param <ProfileConfigurationType> configuration type for this profile
738 protected class SAML2ProfileRequestContext<RequestType extends RequestAbstractType, ResponseType extends StatusResponseType, ProfileConfigurationType extends AbstractSAML2ProfileConfiguration>
739 extends SAMLProfileRequestContext {
741 /** SAML request message. */
742 private RequestType samlRequest;
744 /** SAML response message. */
745 private ResponseType samlResponse;
747 /** Request profile configuration. */
748 private ProfileConfigurationType profileConfiguration;
750 /** The NameID of the subject of this request. */
751 private NameID subjectNameID;
753 /** The request failure status. */
754 private Status failureStatus;
759 * @param request current profile request
760 * @param response current profile response
762 public SAML2ProfileRequestContext(ProfileRequest<ServletRequest> request,
763 ProfileResponse<ServletResponse> response) {
764 super(request, response);
768 * Gets the NameID of the subject of this request.
770 * @return NameID of the subject of this request
772 public NameID getSubjectNameID() {
773 return subjectNameID;
777 * Sets the NameID of the subject of this request.
779 * @param nameID NameID of the subject of this request
781 public void setSubjectNameID(NameID nameID) {
782 subjectNameID = nameID;
786 * Gets the profile configuration for this request.
788 * @return profile configuration for this request
790 public ProfileConfigurationType getProfileConfiguration() {
791 return profileConfiguration;
795 * Sets the profile configuration for this request.
797 * @param configuration profile configuration for this request
799 public void setProfileConfiguration(ProfileConfigurationType configuration) {
800 profileConfiguration = configuration;
804 * Gets the SAML request message.
806 * @return SAML request message
808 public RequestType getSamlRequest() {
813 * Sets the SAML request message.
815 * @param request SAML request message
817 public void setSamlRequest(RequestType request) {
818 samlRequest = request;
822 * Gets the SAML response message.
824 * @return SAML response message
826 public ResponseType getSamlResponse() {
831 * Sets the SAML response message.
833 * @param response SAML response message
835 public void setSamlResponse(ResponseType response) {
836 samlResponse = response;
840 * Gets the status reflecting a request failure.
842 * @return status reflecting a request failure
844 public Status getFailureStatus() {
845 return failureStatus;
849 * Sets the status reflecting a request failure.
851 * @param status status reflecting a request failure
853 public void setFailureStatus(Status status) {
854 failureStatus = status;