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.util.ArrayList;
22 import javax.servlet.RequestDispatcher;
23 import javax.servlet.ServletException;
24 import javax.servlet.http.HttpServletRequest;
25 import javax.servlet.http.HttpSession;
27 import org.opensaml.common.SAMLObjectBuilder;
28 import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
29 import org.opensaml.common.xml.SAMLConstants;
30 import org.opensaml.saml2.binding.AuthnResponseEndpointSelector;
31 import org.opensaml.saml2.core.AttributeStatement;
32 import org.opensaml.saml2.core.AuthnContext;
33 import org.opensaml.saml2.core.AuthnContextClassRef;
34 import org.opensaml.saml2.core.AuthnContextDeclRef;
35 import org.opensaml.saml2.core.AuthnRequest;
36 import org.opensaml.saml2.core.AuthnStatement;
37 import org.opensaml.saml2.core.RequestedAuthnContext;
38 import org.opensaml.saml2.core.Response;
39 import org.opensaml.saml2.core.Statement;
40 import org.opensaml.saml2.core.StatusCode;
41 import org.opensaml.saml2.core.Subject;
42 import org.opensaml.saml2.core.SubjectLocality;
43 import org.opensaml.saml2.metadata.AssertionConsumerService;
44 import org.opensaml.saml2.metadata.Endpoint;
45 import org.opensaml.saml2.metadata.EntityDescriptor;
46 import org.opensaml.saml2.metadata.IDPSSODescriptor;
47 import org.opensaml.saml2.metadata.SPSSODescriptor;
48 import org.opensaml.saml2.metadata.provider.MetadataProvider;
49 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
50 import org.opensaml.ws.message.decoder.MessageDecodingException;
51 import org.opensaml.ws.transport.http.HTTPInTransport;
52 import org.opensaml.ws.transport.http.HTTPOutTransport;
53 import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
54 import org.opensaml.ws.transport.http.HttpServletResponseAdapter;
55 import org.opensaml.xml.io.MarshallingException;
56 import org.opensaml.xml.io.UnmarshallingException;
57 import org.opensaml.xml.security.SecurityException;
58 import org.opensaml.xml.util.DatatypeHelper;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
62 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
63 import edu.internet2.middleware.shibboleth.common.relyingparty.ProfileConfiguration;
64 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
65 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.SSOConfiguration;
66 import edu.internet2.middleware.shibboleth.common.util.HttpHelper;
67 import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
68 import edu.internet2.middleware.shibboleth.idp.authn.Saml2LoginContext;
70 /** SAML 2.0 SSO request profile handler. */
71 public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
74 private final Logger log = LoggerFactory.getLogger(SSOProfileHandler.class);
76 /** Builder of AuthnStatement objects. */
77 private SAMLObjectBuilder<AuthnStatement> authnStatementBuilder;
79 /** Builder of AuthnContext objects. */
80 private SAMLObjectBuilder<AuthnContext> authnContextBuilder;
82 /** Builder of AuthnContextClassRef objects. */
83 private SAMLObjectBuilder<AuthnContextClassRef> authnContextClassRefBuilder;
85 /** Builder of AuthnContextDeclRef objects. */
86 private SAMLObjectBuilder<AuthnContextDeclRef> authnContextDeclRefBuilder;
88 /** Builder of SubjectLocality objects. */
89 private SAMLObjectBuilder<SubjectLocality> subjectLocalityBuilder;
91 /** URL of the authentication manager servlet. */
92 private String authenticationManagerPath;
94 /** URI of request decoder. */
95 private String decodingBinding;
100 * @param authnManagerPath path to the authentication manager servlet
102 @SuppressWarnings("unchecked")
103 public SSOProfileHandler(String authnManagerPath) {
106 authenticationManagerPath = authnManagerPath;
108 authnStatementBuilder = (SAMLObjectBuilder<AuthnStatement>) getBuilderFactory().getBuilder(
109 AuthnStatement.DEFAULT_ELEMENT_NAME);
110 authnContextBuilder = (SAMLObjectBuilder<AuthnContext>) getBuilderFactory().getBuilder(
111 AuthnContext.DEFAULT_ELEMENT_NAME);
112 authnContextClassRefBuilder = (SAMLObjectBuilder<AuthnContextClassRef>) getBuilderFactory().getBuilder(
113 AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
114 authnContextDeclRefBuilder = (SAMLObjectBuilder<AuthnContextDeclRef>) getBuilderFactory().getBuilder(
115 AuthnContextDeclRef.DEFAULT_ELEMENT_NAME);
116 subjectLocalityBuilder = (SAMLObjectBuilder<SubjectLocality>) getBuilderFactory().getBuilder(
117 SubjectLocality.DEFAULT_ELEMENT_NAME);
121 public String getProfileId() {
122 return "urn:mace:shibboleth:2.0:idp:profiles:saml2:request:sso";
126 public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
127 HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
128 HttpSession httpSession = servletRequest.getSession(true);
129 LoginContext loginContext = (LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
131 if (loginContext == null) {
132 log.debug("User session does not contain a login context, processing as first leg of request");
133 performAuthentication(inTransport, outTransport);
134 } else if (!loginContext.isPrincipalAuthenticated()) {
136 .debug("User session contained a login context but user was not authenticated, processing as first leg of request");
137 performAuthentication(inTransport, outTransport);
139 log.debug("User session contains a login context, processing as second leg of request");
140 completeAuthenticationRequest(inTransport, outTransport);
145 * Creates a {@link Saml2LoginContext} an sends the request off to the AuthenticationManager to begin the process of
146 * authenticating the user.
148 * @param inTransport inbound request transport
149 * @param outTransport outbound response transport
151 * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
152 * authentication manager
154 protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
155 throws ProfileException {
156 HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
157 HttpSession httpSession = servletRequest.getSession();
160 SSORequestContext requestContext = decodeRequest(inTransport, outTransport);
162 String relyingPartyId = requestContext.getInboundMessageIssuer();
163 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
164 ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(SSOConfiguration.PROFILE_ID);
165 if (ssoConfig == null) {
166 log.error("SAML 2 SSO profile is not configured for relying party "
167 + requestContext.getInboundMessageIssuer());
168 throw new ProfileException("SAML 2 SSO profile is not configured for relying party "
169 + requestContext.getInboundMessageIssuer());
172 log.debug("Creating login context and transferring control to authentication engine");
173 Saml2LoginContext loginContext = new Saml2LoginContext(relyingPartyId, requestContext.getRelayState(),
174 requestContext.getInboundSAMLMessage());
175 loginContext.setAuthenticationEngineURL(authenticationManagerPath);
176 loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(servletRequest));
177 if (loginContext.getRequestedAuthenticationMethods().size() == 0) {
178 loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
181 httpSession.setAttribute(Saml2LoginContext.LOGIN_CONTEXT_KEY, loginContext);
182 RequestDispatcher dispatcher = servletRequest.getRequestDispatcher(authenticationManagerPath);
183 dispatcher.forward(servletRequest, ((HttpServletResponseAdapter) outTransport).getWrappedResponse());
184 } catch (MarshallingException e) {
185 httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
186 log.error("Unable to marshall authentication request context");
187 throw new ProfileException("Unable to marshall authentication request context", e);
188 } catch (IOException ex) {
189 httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
190 log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
191 throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
192 } catch (ServletException ex) {
193 httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
194 log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
195 throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
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.
203 * @param inTransport inbound message transport
204 * @param outTransport outbound message transport
206 * @throws ProfileException thrown if the response can not be created and sent back to the relying party
208 protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
209 throws ProfileException {
210 HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
211 HttpSession httpSession = servletRequest.getSession();
213 Saml2LoginContext loginContext = (Saml2LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
214 httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
216 SSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
218 checkSamlVersion(requestContext);
220 Response samlResponse;
222 if (loginContext.getPrincipalName() == null) {
223 log.error("User's login context did not contain a principal, user considered unauthenticiated.");
225 .setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI, null));
226 throw new ProfileException("User failed authentication");
229 if (requestContext.getSubjectNameIdentifier() != null) {
230 log.debug("Authentication request contained a subject with a name identifier, resolving principal from NameID");
231 resolvePrincipal(requestContext);
232 String requestedPrincipalName = requestContext.getPrincipalName();
233 if (!DatatypeHelper.safeEquals(loginContext.getPrincipalName(), requestedPrincipalName)) {
234 log.error("Authentication request identified principal {} but authentication mechanism identified principal {}",
235 requestedPrincipalName, loginContext.getPrincipalName());
236 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI,
238 throw new ProfileException("User failed authentication");
242 resolveAttributes(requestContext);
244 ArrayList<Statement> statements = new ArrayList<Statement>();
245 statements.add(buildAuthnStatement(requestContext));
246 if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
247 AttributeStatement attributeStatement = buildAttributeStatement(requestContext);
248 if (attributeStatement != null) {
249 requestContext.setRequestedAttributes(requestContext.getPrincipalAttributes().keySet());
250 statements.add(attributeStatement);
254 samlResponse = buildResponse(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:bearer", statements);
255 } catch (ProfileException e) {
256 samlResponse = buildErrorResponse(requestContext);
259 requestContext.setOutboundSAMLMessage(samlResponse);
260 requestContext.setOutboundSAMLMessageId(samlResponse.getID());
261 requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
262 encodeResponse(requestContext);
263 writeAuditLogEntry(requestContext);
267 * Decodes an incoming request and stores the information in a created request context.
269 * @param inTransport inbound transport
270 * @param outTransport outbound transport
272 * @return request context with decoded information
274 * @throws ProfileException thrown if the incomming message failed decoding
276 protected SSORequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
277 throws ProfileException {
278 log.debug("Decoding message with decoder binding {}", decodingBinding);
280 SSORequestContext requestContext = new SSORequestContext();
281 requestContext.setMetadataProvider(getMetadataProvider());
282 requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
284 requestContext.setCommunicationProfileId(SSOConfiguration.PROFILE_ID);
285 requestContext.setInboundMessageTransport(inTransport);
286 requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
287 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
289 requestContext.setOutboundMessageTransport(outTransport);
290 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
293 SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
294 requestContext.setMessageDecoder(decoder);
295 decoder.decode(requestContext);
296 return requestContext;
297 } catch (MessageDecodingException e) {
298 log.error("Error decoding authentication request message", e);
299 throw new ProfileException("Error decoding authentication request message", e);
300 } catch (SecurityException e) {
301 log.error("Message did not meet security requirements", e);
302 throw new ProfileException("Message did not meet security requirements", e);
307 * Creates an authentication request context from the current environmental information.
309 * @param loginContext current login context
310 * @param in inbound transport
311 * @param out outbount transport
313 * @return created authentication request context
315 * @throws ProfileException thrown if there is a problem creating the context
317 protected SSORequestContext buildRequestContext(Saml2LoginContext loginContext, HTTPInTransport in,
318 HTTPOutTransport out) throws ProfileException {
319 SSORequestContext requestContext = new SSORequestContext();
321 requestContext.setMessageDecoder(getMessageDecoders().get(getInboundBinding()));
323 requestContext.setLoginContext(loginContext);
324 requestContext.setPrincipalName(loginContext.getPrincipalName());
325 requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
326 requestContext.setUserSession(getUserSession(in));
327 requestContext.setRelayState(loginContext.getRelayState());
329 requestContext.setInboundMessageTransport(in);
330 requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
333 AuthnRequest authnRequest = loginContext.getAuthenticationRequest();
334 requestContext.setInboundMessage(authnRequest);
335 requestContext.setInboundSAMLMessage(loginContext.getAuthenticationRequest());
336 requestContext.setInboundSAMLMessageId(loginContext.getAuthenticationRequest().getID());
338 Subject authnSubject = authnRequest.getSubject();
339 if (authnSubject != null) {
340 requestContext.setSubjectNameIdentifier(authnSubject.getNameID());
342 } catch (UnmarshallingException e) {
343 log.error("Unable to unmarshall authentication request context");
344 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
345 "Error recovering request state"));
346 throw new ProfileException("Error recovering request state", e);
349 requestContext.setOutboundMessageTransport(out);
350 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
352 MetadataProvider metadataProvider = getMetadataProvider();
353 requestContext.setMetadataProvider(metadataProvider);
355 String relyingPartyId = loginContext.getRelyingPartyId();
356 requestContext.setInboundMessageIssuer(relyingPartyId);
358 EntityDescriptor relyingPartyMetadata = metadataProvider.getEntityDescriptor(relyingPartyId);
359 if (relyingPartyMetadata != null) {
360 requestContext.setPeerEntityMetadata(relyingPartyMetadata);
361 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
362 requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata
363 .getSPSSODescriptor(SAMLConstants.SAML20P_NS));
365 } catch (MetadataProviderException e) {
366 log.error("Unable to locate metadata for relying party");
367 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
368 "Error locating relying party metadata"));
369 throw new ProfileException("Error locating relying party metadata");
372 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
373 if (rpConfig == null) {
374 log.error("Unable to retrieve relying party configuration data for entity with ID {}", relyingPartyId);
375 throw new ProfileException("Unable to retrieve relying party configuration data for entity with ID "
378 requestContext.setRelyingPartyConfiguration(rpConfig);
380 SSOConfiguration profileConfig = (SSOConfiguration) rpConfig
381 .getProfileConfiguration(SSOConfiguration.PROFILE_ID);
382 requestContext.setProfileConfiguration(profileConfig);
383 requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
384 if (profileConfig.getSigningCredential() != null) {
385 requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
386 } else if (rpConfig.getDefaultSigningCredential() != null) {
387 requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
389 requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
391 String assertingPartyId = rpConfig.getProviderId();
392 requestContext.setLocalEntityId(assertingPartyId);
395 EntityDescriptor localEntityDescriptor = metadataProvider.getEntityDescriptor(assertingPartyId);
396 if (localEntityDescriptor != null) {
397 requestContext.setLocalEntityMetadata(localEntityDescriptor);
398 requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
399 requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
400 .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
402 } catch (MetadataProviderException e) {
403 log.error("Unable to locate metadata for asserting party");
404 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
405 "Error locating asserting party metadata"));
406 throw new ProfileException("Error locating asserting party metadata");
409 return requestContext;
413 * Creates an authentication statement for the current request.
415 * @param requestContext current request context
417 * @return constructed authentication statement
419 protected AuthnStatement buildAuthnStatement(SSORequestContext requestContext) {
420 Saml2LoginContext loginContext = requestContext.getLoginContext();
422 AuthnContext authnContext = buildAuthnContext(requestContext);
424 AuthnStatement statement = authnStatementBuilder.buildObject();
425 statement.setAuthnContext(authnContext);
426 statement.setAuthnInstant(loginContext.getAuthenticationInstant());
429 statement.setSessionIndex(null);
431 if (loginContext.getAuthenticationDuration() > 0) {
432 statement.setSessionNotOnOrAfter(loginContext.getAuthenticationInstant().plus(
433 loginContext.getAuthenticationDuration()));
436 statement.setSubjectLocality(buildSubjectLocality(requestContext));
442 * Creates an {@link AuthnContext} for a succesful authentication request.
444 * @param requestContext current request
446 * @return the built authn context
448 protected AuthnContext buildAuthnContext(SSORequestContext requestContext) {
449 AuthnContext authnContext = authnContextBuilder.buildObject();
451 Saml2LoginContext loginContext = requestContext.getLoginContext();
452 AuthnRequest authnRequest = requestContext.getInboundSAMLMessage();
453 RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
454 if (requestedAuthnContext != null) {
455 if (requestedAuthnContext.getAuthnContextClassRefs() != null) {
456 for (AuthnContextClassRef classRef : requestedAuthnContext.getAuthnContextClassRefs()) {
457 if (classRef.getAuthnContextClassRef().equals(loginContext.getAuthenticationMethod())) {
458 AuthnContextClassRef ref = authnContextClassRefBuilder.buildObject();
459 ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
460 authnContext.setAuthnContextClassRef(ref);
463 } else if (requestedAuthnContext.getAuthnContextDeclRefs() != null) {
464 for (AuthnContextDeclRef declRef : requestedAuthnContext.getAuthnContextDeclRefs()) {
465 if (declRef.getAuthnContextDeclRef().equals(loginContext.getAuthenticationMethod())) {
466 AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
467 ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
468 authnContext.setAuthnContextDeclRef(ref);
473 AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
474 ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
475 authnContext.setAuthnContextDeclRef(ref);
482 * Constructs the subject locality for the authentication statement.
484 * @param requestContext curent request context
486 * @return subject locality for the authentication statement
488 protected SubjectLocality buildSubjectLocality(SSORequestContext requestContext) {
489 HTTPInTransport transport = (HTTPInTransport) requestContext.getInboundMessageTransport();
490 SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
491 subjectLocality.setAddress(transport.getPeerAddress());
492 subjectLocality.setDNSName(transport.getPeerDomainName());
494 return subjectLocality;
498 * Selects the appropriate endpoint for the relying party and stores it in the request context.
500 * @param requestContext current request context
502 * @return Endpoint selected from the information provided in the request context
504 protected Endpoint selectEndpoint(SSORequestContext requestContext) {
505 AuthnResponseEndpointSelector endpointSelector = new AuthnResponseEndpointSelector();
506 endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
507 endpointSelector.setMetadataProvider(getMetadataProvider());
508 endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
509 endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
510 endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
511 endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
512 return endpointSelector.selectEndpoint();
515 /** Represents the internal state of a SAML 2.0 SSO Request while it's being processed by the IdP. */
516 protected class SSORequestContext extends BaseSAML2ProfileRequestContext<AuthnRequest, Response, SSOConfiguration> {
518 /** Current login context. */
519 private Saml2LoginContext loginContext;
522 * Gets the current login context.
524 * @return current login context
526 public Saml2LoginContext getLoginContext() {
531 * Sets the current login context.
533 * @param context current login context
535 public void setLoginContext(Saml2LoginContext context) {
536 loginContext = context;