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;
19 import java.util.List;
22 import javax.servlet.http.HttpServletRequest;
24 import org.opensaml.common.IdentifierGenerator;
25 import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
26 import org.opensaml.common.binding.encoding.SAMLMessageEncoder;
27 import org.opensaml.saml2.metadata.Endpoint;
28 import org.opensaml.saml2.metadata.EntityDescriptor;
29 import org.opensaml.saml2.metadata.provider.MetadataProvider;
30 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
31 import org.opensaml.ws.message.encoder.MessageEncodingException;
32 import org.opensaml.ws.security.SecurityPolicyResolver;
33 import org.opensaml.ws.transport.InTransport;
34 import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
35 import org.opensaml.xml.security.credential.Credential;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
39 import edu.internet2.middleware.shibboleth.common.log.AuditLogEntry;
40 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
41 import edu.internet2.middleware.shibboleth.common.profile.provider.AbstractShibbolethProfileHandler;
42 import edu.internet2.middleware.shibboleth.common.profile.provider.BaseSAMLProfileRequestContext;
43 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
44 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartySecurityPolicyResolver;
45 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.AbstractSAMLProfileConfiguration;
46 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.CryptoOperationRequirementLevel;
47 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.SAMLMDRelyingPartyConfigurationManager;
48 import edu.internet2.middleware.shibboleth.idp.session.Session;
51 * Base class for SAML profile handlers.
53 public abstract class AbstractSAMLProfileHandler extends
54 AbstractShibbolethProfileHandler<SAMLMDRelyingPartyConfigurationManager, Session> {
56 /** SAML message audit log. */
57 private final Logger auditLog = LoggerFactory.getLogger(AuditLogEntry.AUDIT_LOGGER_NAME);
60 private final Logger log = LoggerFactory.getLogger(AbstractSAMLProfileHandler.class);
62 /** Generator of IDs which may be used for SAML assertions, requests, etc. */
63 private IdentifierGenerator idGenerator;
65 /** All the SAML message decoders configured for the IdP. */
66 private Map<String, SAMLMessageDecoder> messageDecoders;
68 /** All the SAML message encoders configured for the IdP. */
69 private Map<String, SAMLMessageEncoder> messageEncoders;
71 /** SAML message binding used by inbound messages. */
72 private String inboundBinding;
74 /** SAML message bindings that may be used by outbound messages. */
75 private List<String> supportedOutboundBindings;
77 /** Resolver used to determine active security policy for an incoming request. */
78 private SecurityPolicyResolver securityPolicyResolver;
81 protected AbstractSAMLProfileHandler() {
86 * Gets the resolver used to determine active security policy for an incoming request.
88 * @return resolver used to determine active security policy for an incoming request
90 public SecurityPolicyResolver getSecurityPolicyResolver() {
91 if (securityPolicyResolver == null) {
92 setSecurityPolicyResolver(new RelyingPartySecurityPolicyResolver(getRelyingPartyConfigurationManager()));
95 return securityPolicyResolver;
99 * Sets the resolver used to determine active security policy for an incoming request.
101 * @param resolver resolver used to determine active security policy for an incoming request
103 public void setSecurityPolicyResolver(SecurityPolicyResolver resolver) {
104 securityPolicyResolver = resolver;
108 * Gets the audit log for this handler.
110 * @return audit log for this handler
112 protected Logger getAduitLog() {
117 * Gets an ID generator which may be used for SAML assertions, requests, etc.
119 * @return ID generator
121 public IdentifierGenerator getIdGenerator() {
126 * Gets the SAML message binding used by inbound messages.
128 * @return SAML message binding used by inbound messages
130 public String getInboundBinding() {
131 return inboundBinding;
135 * Gets all the SAML message decoders configured for the IdP indexed by SAML binding URI.
137 * @return SAML message decoders configured for the IdP indexed by SAML binding URI
139 public Map<String, SAMLMessageDecoder> getMessageDecoders() {
140 return messageDecoders;
144 * Gets all the SAML message encoders configured for the IdP indexed by SAML binding URI.
146 * @return SAML message encoders configured for the IdP indexed by SAML binding URI
148 public Map<String, SAMLMessageEncoder> getMessageEncoders() {
149 return messageEncoders;
153 * A convenience method for retrieving the SAML metadata provider from the relying party manager.
155 * @return the metadata provider or null
157 public MetadataProvider getMetadataProvider() {
158 SAMLMDRelyingPartyConfigurationManager rpcManager = getRelyingPartyConfigurationManager();
159 if (rpcManager != null) {
160 return rpcManager.getMetadataProvider();
167 * Gets the SAML message bindings that may be used by outbound messages.
169 * @return SAML message bindings that may be used by outbound messages
171 public List<String> getSupportedOutboundBindings() {
172 return supportedOutboundBindings;
176 * Gets the user's session, if there is one.
178 * @param inTransport current inbound transport
180 * @return user's session
182 protected Session getUserSession(InTransport inTransport) {
183 HttpServletRequest rawRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
184 return (Session) rawRequest.getAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE);
188 * Gets the user's session based on their principal name.
190 * @param principalName user's principal name
192 * @return the user's session
194 protected Session getUserSession(String principalName) {
195 return getSessionManager().getSession(principalName);
199 * Gets an ID generator which may be used for SAML assertions, requests, etc.
201 * @param generator an ID generator which may be used for SAML assertions, requests, etc
203 public void setIdGenerator(IdentifierGenerator generator) {
204 idGenerator = generator;
208 * Sets the SAML message binding used by inbound messages.
210 * @param binding SAML message binding used by inbound messages
212 public void setInboundBinding(String binding) {
213 inboundBinding = binding;
217 * Sets all the SAML message decoders configured for the IdP indexed by SAML binding URI.
219 * @param decoders SAML message decoders configured for the IdP indexed by SAML binding URI
221 public void setMessageDecoders(Map<String, SAMLMessageDecoder> decoders) {
222 messageDecoders = decoders;
226 * Sets all the SAML message encoders configured for the IdP indexed by SAML binding URI.
228 * @param encoders SAML message encoders configured for the IdP indexed by SAML binding URI
230 public void setMessageEncoders(Map<String, SAMLMessageEncoder> encoders) {
231 messageEncoders = encoders;
235 * Sets the SAML message bindings that may be used by outbound messages.
237 * @param bindings SAML message bindings that may be used by outbound messages
239 public void setSupportedOutboundBindings(List<String> bindings) {
240 supportedOutboundBindings = bindings;
244 * Populates the request context with information.
246 * This method requires the the following request context properties to be populated: inbound message transport,
247 * peer entity ID, metadata provider
249 * This methods populates the following request context properties: user's session, user's principal name, service
250 * authentication method, peer entity metadata, relying party configuration, local entity ID, outbound message
251 * issuer, local entity metadata
253 * @param requestContext current request context
254 * @throws ProfileException thrown if there is a problem looking up the relying party's metadata
256 protected void populateRequestContext(BaseSAMLProfileRequestContext requestContext) throws ProfileException {
257 populateRelyingPartyInformation(requestContext);
258 populateAssertingPartyInformation(requestContext);
259 populateSAMLMessageInformation(requestContext);
260 populateProfileInformation(requestContext);
261 populateUserInformation(requestContext);
265 * Populates the request context with information about the relying party.
267 * This method requires the the following request context properties to be populated: peer entity ID
269 * This methods populates the following request context properties: peer entity metadata, relying party
272 * @param requestContext current request context
273 * @throws ProfileException thrown if there is a problem looking up the relying party's metadata
275 protected void populateRelyingPartyInformation(BaseSAMLProfileRequestContext requestContext)
276 throws ProfileException {
277 MetadataProvider metadataProvider = requestContext.getMetadataProvider();
278 String relyingPartyId = requestContext.getPeerEntityId();
280 EntityDescriptor relyingPartyMetadata;
282 relyingPartyMetadata = metadataProvider.getEntityDescriptor(relyingPartyId);
283 } catch (MetadataProviderException e) {
284 log.error("Error looking up metadata for relying party " + relyingPartyId, e);
285 throw new ProfileException("Error looking up metadata for relying party " + relyingPartyId);
288 RelyingPartyConfiguration rpConfig = null;
289 if (relyingPartyMetadata != null) {
290 requestContext.setPeerEntityMetadata(relyingPartyMetadata);
291 rpConfig = getRelyingPartyConfiguration(relyingPartyId);
293 log.warn("No metadata for relying party {}, treating party as anonymous", relyingPartyId);
294 rpConfig = getRelyingPartyConfigurationManager().getAnonymousRelyingConfiguration();
297 if (rpConfig == null) {
298 log.error("Unable to retrieve relying party configuration data for entity with ID {}", relyingPartyId);
299 throw new ProfileException("Unable to retrieve relying party configuration data for entity with ID "
302 requestContext.setRelyingPartyConfiguration(rpConfig);
306 * Populates the request context with information about the asserting party. Unless overridden,
307 * {@link #populateRequestContext(BaseSAMLProfileRequestContext)} has already invoked
308 * {@link #populateRelyingPartyInformation(BaseSAMLProfileRequestContext)} has already been invoked and the
309 * properties it provides are available in the request context.
311 * This method requires the the following request context properties to be populated: metadata provider, relying
312 * party configuration
314 * This methods populates the following request context properties: local entity ID, outbound message issuer, local
317 * @param requestContext current request context
318 * @throws ProfileException thrown if there is a problem looking up the asserting party's metadata
320 protected void populateAssertingPartyInformation(BaseSAMLProfileRequestContext requestContext)
321 throws ProfileException {
322 String assertingPartyId = requestContext.getRelyingPartyConfiguration().getProviderId();
323 requestContext.setLocalEntityId(assertingPartyId);
324 requestContext.setOutboundMessageIssuer(assertingPartyId);
327 EntityDescriptor localEntityDescriptor = requestContext.getMetadataProvider().getEntityDescriptor(
329 if (localEntityDescriptor != null) {
330 requestContext.setLocalEntityMetadata(localEntityDescriptor);
332 } catch (MetadataProviderException e) {
333 log.error("Error looking up metadata for asserting party " + assertingPartyId, e);
334 throw new ProfileException("Error looking up metadata for asserting party " + assertingPartyId);
339 * Populates the request context with information from the inbound SAML message. Unless overridden,
340 * {@link #populateRequestContext(BaseSAMLProfileRequestContext)} has already invoked
341 * {@link #populateRelyingPartyInformation(BaseSAMLProfileRequestContext)},and
342 * {@link #populateAssertingPartyInformation(BaseSAMLProfileRequestContext)} have already been invoked and the
343 * properties they provide are available in the request context.
346 * @param requestContext current request context
348 * @throws ProfileException thrown if there is a problem populating the request context with information
350 protected abstract void populateSAMLMessageInformation(BaseSAMLProfileRequestContext requestContext)
351 throws ProfileException;
354 * Populates the request context with the information about the profile. Unless overridden,
355 * {@link #populateRequestContext(BaseSAMLProfileRequestContext)} has already invoked
356 * {@link #populateRelyingPartyInformation(BaseSAMLProfileRequestContext)},
357 * {@link #populateAssertingPartyInformation(BaseSAMLProfileRequestContext)}, and
358 * {@link #populateSAMLMessageInformation(BaseSAMLProfileRequestContext)} have already been invoked and the
359 * properties they provide are available in the request context.
361 * This method requires the the following request context properties to be populated: relying party configuration
363 * This methods populates the following request context properties: communication profile ID, profile configuration,
364 * outbound message artifact type, peer entity endpoint
366 * @param requestContext current request context
368 * @throws ProfileException thrown if there is a problem populating the profile information
370 protected void populateProfileInformation(BaseSAMLProfileRequestContext requestContext) throws ProfileException {
371 requestContext.setCommunicationProfileId(getProfileId());
372 AbstractSAMLProfileConfiguration profileConfig = (AbstractSAMLProfileConfiguration) requestContext
373 .getRelyingPartyConfiguration().getProfileConfiguration(getProfileId());
374 if (profileConfig != null) {
375 requestContext.setProfileConfiguration(profileConfig);
376 requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
379 requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
383 * Populates the request context with the information about the user if they have an existing session. Unless
384 * overridden, {@link #populateRequestContext(BaseSAMLProfileRequestContext)} has already invoked
385 * {@link #populateRelyingPartyInformation(BaseSAMLProfileRequestContext)},
386 * {@link #populateAssertingPartyInformation(BaseSAMLProfileRequestContext)},
387 * {@link #populateProfileInformation(BaseSAMLProfileRequestContext)}, and
388 * {@link #populateSAMLMessageInformation(BaseSAMLProfileRequestContext)} have already been invoked and the
389 * properties they provide are available in the request context.
391 * This method should populate: user's session, user's principal name, and service authentication method
393 * @param requestContext current request context
395 * @throws ProfileException thrown if there is a problem populating the user's information
397 protected abstract void populateUserInformation(BaseSAMLProfileRequestContext requestContext)
398 throws ProfileException;
401 * Selects the appropriate endpoint for the relying party and stores it in the request context.
403 * @param requestContext current request context
405 * @return Endpoint selected from the information provided in the request context
407 * @throws ProfileException thrown if there is a problem selecting a response endpoint
409 protected abstract Endpoint selectEndpoint(BaseSAMLProfileRequestContext requestContext) throws ProfileException;
412 * Encodes the request's SAML response and writes it to the servlet response.
414 * @param requestContext current request context
416 * @throws ProfileException thrown if no message encoder is registered for this profiles binding
418 protected void encodeResponse(BaseSAMLProfileRequestContext requestContext) throws ProfileException {
421 Endpoint peerEndpoint = requestContext.getPeerEntityEndpoint();
422 if (peerEndpoint == null) {
424 .error("No return endpoint available for relying party {}", requestContext
425 .getInboundMessageIssuer());
426 throw new ProfileException("No peer endpoint available to which to send SAML response");
429 SAMLMessageEncoder encoder = getMessageEncoders().get(requestContext.getPeerEntityEndpoint().getBinding());
430 if (encoder == null) {
431 log.error("No outbound message encoder configured for binding {}", requestContext
432 .getPeerEntityEndpoint().getBinding());
433 throw new ProfileException("No outbound message encoder configured for binding "
434 + requestContext.getPeerEntityEndpoint().getBinding());
437 AbstractSAMLProfileConfiguration profileConfig = (AbstractSAMLProfileConfiguration) requestContext
438 .getProfileConfiguration();
439 if (profileConfig.getSignResponses() == CryptoOperationRequirementLevel.always
440 || (profileConfig.getSignResponses() == CryptoOperationRequirementLevel.conditional && !encoder
441 .providesMessageIntegrity(requestContext))) {
442 Credential signingCredential = null;
443 if (profileConfig.getSigningCredential() != null) {
444 signingCredential = profileConfig.getSigningCredential();
445 } else if (requestContext.getRelyingPartyConfiguration().getDefaultSigningCredential() != null) {
446 signingCredential = requestContext.getRelyingPartyConfiguration().getDefaultSigningCredential();
449 if (signingCredential == null) {
450 throw new ProfileException(
451 "Signing of responses is required but no signing credential is available");
454 requestContext.setOutboundSAMLMessageSigningCredential(signingCredential);
457 log.debug("Encoding response to SAML request {} from relying party {}", requestContext
458 .getInboundSAMLMessageId(), requestContext.getInboundMessageIssuer());
460 requestContext.setMessageEncoder(encoder);
461 encoder.encode(requestContext);
462 } catch (MessageEncodingException e) {
463 throw new ProfileException("Unable to encode response to relying party: "
464 + requestContext.getInboundMessageIssuer(), e);
469 * Writes an aduit log entry indicating the successful response to the attribute request.
471 * @param context current request context
473 protected void writeAuditLogEntry(BaseSAMLProfileRequestContext context) {
474 AuditLogEntry auditLogEntry = new AuditLogEntry();
475 auditLogEntry.setMessageProfile(getProfileId());
476 auditLogEntry.setPrincipalAuthenticationMethod(context.getPrincipalAuthenticationMethod());
477 auditLogEntry.setPrincipalName(context.getPrincipalName());
478 auditLogEntry.setAssertingPartyId(context.getLocalEntityId());
479 auditLogEntry.setRelyingPartyId(context.getInboundMessageIssuer());
480 auditLogEntry.setRequestBinding(context.getMessageDecoder().getBindingURI());
481 auditLogEntry.setRequestId(context.getInboundSAMLMessageId());
482 auditLogEntry.setResponseBinding(context.getMessageEncoder().getBindingURI());
483 auditLogEntry.setResponseId(context.getOutboundSAMLMessageId());
484 if (context.getReleasedAttributes() != null) {
485 auditLogEntry.getReleasedAttributes().addAll(context.getReleasedAttributes());
488 getAduitLog().info(auditLogEntry.toString());