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.AuthnContext;
32 import org.opensaml.saml2.core.AuthnContextClassRef;
33 import org.opensaml.saml2.core.AuthnContextDeclRef;
34 import org.opensaml.saml2.core.AuthnRequest;
35 import org.opensaml.saml2.core.AuthnStatement;
36 import org.opensaml.saml2.core.RequestedAuthnContext;
37 import org.opensaml.saml2.core.Response;
38 import org.opensaml.saml2.core.Statement;
39 import org.opensaml.saml2.core.StatusCode;
40 import org.opensaml.saml2.core.SubjectLocality;
41 import org.opensaml.saml2.metadata.AssertionConsumerService;
42 import org.opensaml.saml2.metadata.Endpoint;
43 import org.opensaml.saml2.metadata.EntityDescriptor;
44 import org.opensaml.saml2.metadata.IDPSSODescriptor;
45 import org.opensaml.saml2.metadata.SPSSODescriptor;
46 import org.opensaml.saml2.metadata.provider.MetadataProvider;
47 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
48 import org.opensaml.ws.message.decoder.MessageDecodingException;
49 import org.opensaml.ws.transport.http.HTTPInTransport;
50 import org.opensaml.ws.transport.http.HTTPOutTransport;
51 import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
52 import org.opensaml.ws.transport.http.HttpServletResponseAdapter;
53 import org.opensaml.xml.io.MarshallingException;
54 import org.opensaml.xml.io.UnmarshallingException;
55 import org.opensaml.xml.security.SecurityException;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
59 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
60 import edu.internet2.middleware.shibboleth.common.relyingparty.ProfileConfiguration;
61 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
62 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.SSOConfiguration;
63 import edu.internet2.middleware.shibboleth.common.util.HttpHelper;
64 import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
65 import edu.internet2.middleware.shibboleth.idp.authn.Saml2LoginContext;
67 /** SAML 2.0 SSO request profile handler. */
68 public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
71 private final Logger log = LoggerFactory.getLogger(SSOProfileHandler.class);
73 /** Builder of AuthnStatement objects. */
74 private SAMLObjectBuilder<AuthnStatement> authnStatementBuilder;
76 /** Builder of AuthnContext objects. */
77 private SAMLObjectBuilder<AuthnContext> authnContextBuilder;
79 /** Builder of AuthnContextClassRef objects. */
80 private SAMLObjectBuilder<AuthnContextClassRef> authnContextClassRefBuilder;
82 /** Builder of AuthnContextDeclRef objects. */
83 private SAMLObjectBuilder<AuthnContextDeclRef> authnContextDeclRefBuilder;
85 /** Builder of SubjectLocality objects. */
86 private SAMLObjectBuilder<SubjectLocality> subjectLocalityBuilder;
88 /** URL of the authentication manager servlet. */
89 private String authenticationManagerPath;
91 /** URI of request decoder. */
92 private String decodingBinding;
97 * @param authnManagerPath path to the authentication manager servlet
99 @SuppressWarnings("unchecked")
100 public SSOProfileHandler(String authnManagerPath) {
103 authenticationManagerPath = authnManagerPath;
105 authnStatementBuilder = (SAMLObjectBuilder<AuthnStatement>) getBuilderFactory().getBuilder(
106 AuthnStatement.DEFAULT_ELEMENT_NAME);
107 authnContextBuilder = (SAMLObjectBuilder<AuthnContext>) getBuilderFactory().getBuilder(
108 AuthnContext.DEFAULT_ELEMENT_NAME);
109 authnContextClassRefBuilder = (SAMLObjectBuilder<AuthnContextClassRef>) getBuilderFactory().getBuilder(
110 AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
111 authnContextDeclRefBuilder = (SAMLObjectBuilder<AuthnContextDeclRef>) getBuilderFactory().getBuilder(
112 AuthnContextDeclRef.DEFAULT_ELEMENT_NAME);
113 subjectLocalityBuilder = (SAMLObjectBuilder<SubjectLocality>) getBuilderFactory().getBuilder(
114 SubjectLocality.DEFAULT_ELEMENT_NAME);
118 public String getProfileId() {
119 return "urn:mace:shibboleth:2.0:idp:profiles:saml2:request:sso";
123 public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
124 HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
125 HttpSession httpSession = servletRequest.getSession(true);
127 if (httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY) == null) {
128 performAuthentication(inTransport, outTransport);
130 completeAuthenticationRequest(inTransport, outTransport);
135 * Creates a {@link Saml2LoginContext} an sends the request off to the AuthenticationManager to begin the process of
136 * authenticating the user.
138 * @param inTransport inbound request transport
139 * @param outTransport outbound response transport
141 * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
142 * authentication manager
144 protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
145 throws ProfileException {
146 HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
149 SSORequestContext requestContext = decodeRequest(inTransport, outTransport);
151 String relyingPartyId = requestContext.getInboundMessageIssuer();
152 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
153 ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(SSOConfiguration.PROFILE_ID);
154 if (ssoConfig == null) {
155 log.error("SAML 2 SSO profile is not configured for relying party "
156 + requestContext.getInboundMessageIssuer());
157 throw new ProfileException("SAML 2 SSO profile is not configured for relying party "
158 + requestContext.getInboundMessageIssuer());
161 log.debug("Creating login context and transferring control to authentication engine");
162 Saml2LoginContext loginContext = new Saml2LoginContext(relyingPartyId, requestContext.getRelayState(),
163 requestContext.getInboundSAMLMessage());
164 loginContext.setAuthenticationEngineURL(authenticationManagerPath);
165 loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(servletRequest));
166 if (loginContext.getRequestedAuthenticationMethods().size() == 0) {
167 loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
170 HttpSession httpSession = servletRequest.getSession();
171 httpSession.setAttribute(Saml2LoginContext.LOGIN_CONTEXT_KEY, loginContext);
172 RequestDispatcher dispatcher = servletRequest.getRequestDispatcher(authenticationManagerPath);
173 dispatcher.forward(servletRequest, ((HttpServletResponseAdapter) outTransport).getWrappedResponse());
174 } catch (MarshallingException e) {
175 log.error("Unable to marshall authentication request context");
176 throw new ProfileException("Unable to marshall authentication request context", e);
177 } catch (IOException ex) {
178 log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
179 throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
180 } catch (ServletException ex) {
181 log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
182 throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
187 * Creates a response to the {@link AuthnRequest} and sends the user, with response in tow, back to the relying
188 * party after they've been authenticated.
190 * @param inTransport inbound message transport
191 * @param outTransport outbound message transport
193 * @throws ProfileException thrown if the response can not be created and sent back to the relying party
195 protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
196 throws ProfileException {
197 HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
198 HttpSession httpSession = servletRequest.getSession();
200 Saml2LoginContext loginContext = (Saml2LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
201 httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
203 SSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
205 checkSamlVersion(requestContext);
207 Response samlResponse;
209 if (loginContext.getPrincipalName() == null) {
210 log.error("User's login context did not contain a principal, user considered unauthenticiated.");
212 .setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI, null));
213 throw new ProfileException("User failed authentication");
216 resolveAttributes(requestContext);
218 ArrayList<Statement> statements = new ArrayList<Statement>();
219 statements.add(buildAuthnStatement(requestContext));
220 if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
221 requestContext.setRequestedAttributes(requestContext.getPrincipalAttributes().keySet());
222 statements.add(buildAttributeStatement(requestContext));
225 samlResponse = buildResponse(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:bearer", statements);
226 } catch (ProfileException e) {
227 samlResponse = buildErrorResponse(requestContext);
230 requestContext.setOutboundSAMLMessage(samlResponse);
231 requestContext.setOutboundSAMLMessageId(samlResponse.getID());
232 requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
233 encodeResponse(requestContext);
234 writeAuditLogEntry(requestContext);
238 * Decodes an incoming request and stores the information in a created request context.
240 * @param inTransport inbound transport
241 * @param outTransport outbound transport
243 * @return request context with decoded information
245 * @throws ProfileException thrown if the incomming message failed decoding
247 protected SSORequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
248 throws ProfileException {
249 log.debug("Decoding message with decoder binding {}", decodingBinding);
251 SSORequestContext requestContext = new SSORequestContext();
252 requestContext.setMetadataProvider(getMetadataProvider());
253 requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
255 requestContext.setCommunicationProfileId(SSOConfiguration.PROFILE_ID);
256 requestContext.setInboundMessageTransport(inTransport);
257 requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
258 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
260 requestContext.setOutboundMessageTransport(outTransport);
261 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
264 SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
265 requestContext.setMessageDecoder(decoder);
266 decoder.decode(requestContext);
267 return requestContext;
268 } catch (MessageDecodingException e) {
269 log.error("Error decoding authentication request message", e);
270 throw new ProfileException("Error decoding authentication request message", e);
271 } catch (SecurityException e) {
272 log.error("Message did not meet security requirements", e);
273 throw new ProfileException("Message did not meet security requirements", e);
278 * Creates an authentication request context from the current environmental information.
280 * @param loginContext current login context
281 * @param in inbound transport
282 * @param out outbount transport
284 * @return created authentication request context
286 * @throws ProfileException thrown if there is a problem creating the context
288 protected SSORequestContext buildRequestContext(Saml2LoginContext loginContext, HTTPInTransport in,
289 HTTPOutTransport out) throws ProfileException {
290 SSORequestContext requestContext = new SSORequestContext();
292 requestContext.setMessageDecoder(getMessageDecoders().get(getInboundBinding()));
294 requestContext.setLoginContext(loginContext);
295 requestContext.setPrincipalName(loginContext.getPrincipalName());
296 requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
297 requestContext.setUserSession(getUserSession(in));
298 requestContext.setRelayState(loginContext.getRelayState());
300 requestContext.setInboundMessageTransport(in);
301 requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
304 requestContext.setInboundMessage(loginContext.getAuthenticationRequest());
305 requestContext.setInboundSAMLMessage(loginContext.getAuthenticationRequest());
306 requestContext.setInboundSAMLMessageId(loginContext.getAuthenticationRequest().getID());
307 } catch (UnmarshallingException e) {
308 log.error("Unable to unmarshall authentication request context");
309 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
310 "Error recovering request state"));
311 throw new ProfileException("Error recovering request state", e);
314 requestContext.setOutboundMessageTransport(out);
315 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
317 MetadataProvider metadataProvider = getMetadataProvider();
318 requestContext.setMetadataProvider(metadataProvider);
320 String relyingPartyId = loginContext.getRelyingPartyId();
321 requestContext.setInboundMessageIssuer(relyingPartyId);
323 EntityDescriptor relyingPartyMetadata = metadataProvider.getEntityDescriptor(relyingPartyId);
324 if (relyingPartyMetadata != null) {
325 requestContext.setPeerEntityMetadata(relyingPartyMetadata);
326 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
327 requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata
328 .getSPSSODescriptor(SAMLConstants.SAML20P_NS));
330 } catch (MetadataProviderException e) {
331 log.error("Unable to locate metadata for relying party");
332 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
333 "Error locating relying party metadata"));
334 throw new ProfileException("Error locating relying party metadata");
337 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
338 if (rpConfig == null) {
339 log.error("Unable to retrieve relying party configuration data for entity with ID {}", relyingPartyId);
340 throw new ProfileException("Unable to retrieve relying party configuration data for entity with ID "
343 requestContext.setRelyingPartyConfiguration(rpConfig);
345 SSOConfiguration profileConfig = (SSOConfiguration) rpConfig
346 .getProfileConfiguration(SSOConfiguration.PROFILE_ID);
347 requestContext.setProfileConfiguration(profileConfig);
348 requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
349 if (profileConfig.getSigningCredential() != null) {
350 requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
351 } else if (rpConfig.getDefaultSigningCredential() != null) {
352 requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
354 requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
356 String assertingPartyId = rpConfig.getProviderId();
357 requestContext.setLocalEntityId(assertingPartyId);
360 EntityDescriptor localEntityDescriptor = metadataProvider.getEntityDescriptor(assertingPartyId);
361 if (localEntityDescriptor != null) {
362 requestContext.setLocalEntityMetadata(localEntityDescriptor);
363 requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
364 requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
365 .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
367 } catch (MetadataProviderException e) {
368 log.error("Unable to locate metadata for asserting party");
369 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
370 "Error locating asserting party metadata"));
371 throw new ProfileException("Error locating asserting party metadata");
374 return requestContext;
378 * Creates an authentication statement for the current request.
380 * @param requestContext current request context
382 * @return constructed authentication statement
384 protected AuthnStatement buildAuthnStatement(SSORequestContext requestContext) {
385 Saml2LoginContext loginContext = requestContext.getLoginContext();
387 AuthnContext authnContext = buildAuthnContext(requestContext);
389 AuthnStatement statement = authnStatementBuilder.buildObject();
390 statement.setAuthnContext(authnContext);
391 statement.setAuthnInstant(loginContext.getAuthenticationInstant());
394 statement.setSessionIndex(null);
396 if (loginContext.getAuthenticationDuration() > 0) {
397 statement.setSessionNotOnOrAfter(loginContext.getAuthenticationInstant().plus(
398 loginContext.getAuthenticationDuration()));
401 statement.setSubjectLocality(buildSubjectLocality(requestContext));
407 * Creates an {@link AuthnContext} for a succesful authentication request.
409 * @param requestContext current request
411 * @return the built authn context
413 protected AuthnContext buildAuthnContext(SSORequestContext requestContext) {
414 AuthnContext authnContext = authnContextBuilder.buildObject();
416 Saml2LoginContext loginContext = requestContext.getLoginContext();
417 AuthnRequest authnRequest = requestContext.getInboundSAMLMessage();
418 RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
419 if (requestedAuthnContext != null) {
420 if (requestedAuthnContext.getAuthnContextClassRefs() != null) {
421 for (AuthnContextClassRef classRef : requestedAuthnContext.getAuthnContextClassRefs()) {
422 if (classRef.getAuthnContextClassRef().equals(loginContext.getAuthenticationMethod())) {
423 AuthnContextClassRef ref = authnContextClassRefBuilder.buildObject();
424 ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
425 authnContext.setAuthnContextClassRef(ref);
428 } else if (requestedAuthnContext.getAuthnContextDeclRefs() != null) {
429 for (AuthnContextDeclRef declRef : requestedAuthnContext.getAuthnContextDeclRefs()) {
430 if (declRef.getAuthnContextDeclRef().equals(loginContext.getAuthenticationMethod())) {
431 AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
432 ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
433 authnContext.setAuthnContextDeclRef(ref);
438 AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
439 ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
440 authnContext.setAuthnContextDeclRef(ref);
447 * Constructs the subject locality for the authentication statement.
449 * @param requestContext curent request context
451 * @return subject locality for the authentication statement
453 protected SubjectLocality buildSubjectLocality(SSORequestContext requestContext) {
454 HTTPInTransport transport = (HTTPInTransport) requestContext.getInboundMessageTransport();
455 SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
456 subjectLocality.setAddress(transport.getPeerAddress());
457 subjectLocality.setDNSName(transport.getPeerDomainName());
459 return subjectLocality;
463 * Selects the appropriate endpoint for the relying party and stores it in the request context.
465 * @param requestContext current request context
467 * @return Endpoint selected from the information provided in the request context
469 protected Endpoint selectEndpoint(SSORequestContext requestContext) {
470 AuthnResponseEndpointSelector endpointSelector = new AuthnResponseEndpointSelector();
471 endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
472 endpointSelector.setMetadataProvider(getMetadataProvider());
473 endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
474 endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
475 endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
476 endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
477 return endpointSelector.selectEndpoint();
480 /** Represents the internal state of a SAML 2.0 SSO Request while it's being processed by the IdP. */
481 protected class SSORequestContext extends BaseSAML2ProfileRequestContext<AuthnRequest, Response, SSOConfiguration> {
483 /** Current login context. */
484 private Saml2LoginContext loginContext;
487 * Gets the current login context.
489 * @return current login context
491 public Saml2LoginContext getLoginContext() {
496 * Sets the current login context.
498 * @param context current login context
500 public void setLoginContext(Saml2LoginContext context) {
501 loginContext = context;