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.getPrincipalAttributes().isEmpty()) {
222 requestContext.setRequestedAttributes(requestContext.getPrincipalAttributes().keySet());
223 statements.add(buildAttributeStatement(requestContext));
226 samlResponse = buildResponse(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:bearer", statements);
227 } catch (ProfileException e) {
228 samlResponse = buildErrorResponse(requestContext);
231 requestContext.setOutboundSAMLMessage(samlResponse);
232 requestContext.setOutboundSAMLMessageId(samlResponse.getID());
233 requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
234 encodeResponse(requestContext);
235 writeAuditLogEntry(requestContext);
239 * Decodes an incoming request and stores the information in a created request context.
241 * @param inTransport inbound transport
242 * @param outTransport outbound transport
244 * @return request context with decoded information
246 * @throws ProfileException thrown if the incomming message failed decoding
248 protected SSORequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
249 throws ProfileException {
250 log.debug("Decoding message with decoder binding {}", decodingBinding);
252 SSORequestContext requestContext = new SSORequestContext();
253 requestContext.setMetadataProvider(getMetadataProvider());
254 requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
256 requestContext.setCommunicationProfileId(SSOConfiguration.PROFILE_ID);
257 requestContext.setInboundMessageTransport(inTransport);
258 requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
259 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
261 requestContext.setOutboundMessageTransport(outTransport);
262 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
265 SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
266 requestContext.setMessageDecoder(decoder);
267 decoder.decode(requestContext);
268 return requestContext;
269 } catch (MessageDecodingException e) {
270 log.error("Error decoding authentication request message", e);
271 throw new ProfileException("Error decoding authentication request message", e);
272 } catch (SecurityException e) {
273 log.error("Message did not meet security requirements", e);
274 throw new ProfileException("Message did not meet security requirements", e);
279 * Creates an authentication request context from the current environmental information.
281 * @param loginContext current login context
282 * @param in inbound transport
283 * @param out outbount transport
285 * @return created authentication request context
287 * @throws ProfileException thrown if there is a problem creating the context
289 protected SSORequestContext buildRequestContext(Saml2LoginContext loginContext, HTTPInTransport in,
290 HTTPOutTransport out) throws ProfileException {
291 SSORequestContext requestContext = new SSORequestContext();
293 requestContext.setMessageDecoder(getMessageDecoders().get(getInboundBinding()));
295 requestContext.setLoginContext(loginContext);
296 requestContext.setPrincipalName(loginContext.getPrincipalName());
297 requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
298 requestContext.setUserSession(getUserSession(in));
299 requestContext.setRelayState(loginContext.getRelayState());
301 requestContext.setInboundMessageTransport(in);
302 requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
305 requestContext.setInboundMessage(loginContext.getAuthenticationRequest());
306 requestContext.setInboundSAMLMessage(loginContext.getAuthenticationRequest());
307 requestContext.setInboundSAMLMessageId(loginContext.getAuthenticationRequest().getID());
308 } catch (UnmarshallingException e) {
309 log.error("Unable to unmarshall authentication request context");
310 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
311 "Error recovering request state"));
312 throw new ProfileException("Error recovering request state", e);
315 requestContext.setOutboundMessageTransport(out);
316 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
318 MetadataProvider metadataProvider = getMetadataProvider();
319 requestContext.setMetadataProvider(metadataProvider);
321 String relyingPartyId = loginContext.getRelyingPartyId();
322 requestContext.setInboundMessageIssuer(relyingPartyId);
324 EntityDescriptor relyingPartyMetadata = metadataProvider.getEntityDescriptor(relyingPartyId);
325 if (relyingPartyMetadata != null) {
326 requestContext.setPeerEntityMetadata(relyingPartyMetadata);
327 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
328 requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata
329 .getSPSSODescriptor(SAMLConstants.SAML20P_NS));
331 } catch (MetadataProviderException e) {
332 log.error("Unable to locate metadata for relying party");
333 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
334 "Error locating relying party metadata"));
335 throw new ProfileException("Error locating relying party metadata");
338 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
339 if (rpConfig == null) {
340 log.error("Unable to retrieve relying party configuration data for entity with ID {}", relyingPartyId);
341 throw new ProfileException("Unable to retrieve relying party configuration data for entity with ID "
344 requestContext.setRelyingPartyConfiguration(rpConfig);
346 SSOConfiguration profileConfig = (SSOConfiguration) rpConfig
347 .getProfileConfiguration(SSOConfiguration.PROFILE_ID);
348 requestContext.setProfileConfiguration(profileConfig);
349 requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
350 if (profileConfig.getSigningCredential() != null) {
351 requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
352 } else if (rpConfig.getDefaultSigningCredential() != null) {
353 requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
355 requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
357 String assertingPartyId = rpConfig.getProviderId();
358 requestContext.setLocalEntityId(assertingPartyId);
361 EntityDescriptor localEntityDescriptor = metadataProvider.getEntityDescriptor(assertingPartyId);
362 if (localEntityDescriptor != null) {
363 requestContext.setLocalEntityMetadata(localEntityDescriptor);
364 requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
365 requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
366 .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
368 } catch (MetadataProviderException e) {
369 log.error("Unable to locate metadata for asserting party");
370 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
371 "Error locating asserting party metadata"));
372 throw new ProfileException("Error locating asserting party metadata");
375 return requestContext;
379 * Creates an authentication statement for the current request.
381 * @param requestContext current request context
383 * @return constructed authentication statement
385 protected AuthnStatement buildAuthnStatement(SSORequestContext requestContext) {
386 Saml2LoginContext loginContext = requestContext.getLoginContext();
388 AuthnContext authnContext = buildAuthnContext(requestContext);
390 AuthnStatement statement = authnStatementBuilder.buildObject();
391 statement.setAuthnContext(authnContext);
392 statement.setAuthnInstant(loginContext.getAuthenticationInstant());
395 statement.setSessionIndex(null);
397 if (loginContext.getAuthenticationDuration() > 0) {
398 statement.setSessionNotOnOrAfter(loginContext.getAuthenticationInstant().plus(
399 loginContext.getAuthenticationDuration()));
402 statement.setSubjectLocality(buildSubjectLocality(requestContext));
408 * Creates an {@link AuthnContext} for a succesful authentication request.
410 * @param requestContext current request
412 * @return the built authn context
414 protected AuthnContext buildAuthnContext(SSORequestContext requestContext) {
415 AuthnContext authnContext = authnContextBuilder.buildObject();
417 Saml2LoginContext loginContext = requestContext.getLoginContext();
418 AuthnRequest authnRequest = requestContext.getInboundSAMLMessage();
419 RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
420 if (requestedAuthnContext != null) {
421 if (requestedAuthnContext.getAuthnContextClassRefs() != null) {
422 for (AuthnContextClassRef classRef : requestedAuthnContext.getAuthnContextClassRefs()) {
423 if (classRef.getAuthnContextClassRef().equals(loginContext.getAuthenticationMethod())) {
424 AuthnContextClassRef ref = authnContextClassRefBuilder.buildObject();
425 ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
426 authnContext.setAuthnContextClassRef(ref);
429 } else if (requestedAuthnContext.getAuthnContextDeclRefs() != null) {
430 for (AuthnContextDeclRef declRef : requestedAuthnContext.getAuthnContextDeclRefs()) {
431 if (declRef.getAuthnContextDeclRef().equals(loginContext.getAuthenticationMethod())) {
432 AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
433 ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
434 authnContext.setAuthnContextDeclRef(ref);
439 AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
440 ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
441 authnContext.setAuthnContextDeclRef(ref);
448 * Constructs the subject locality for the authentication statement.
450 * @param requestContext curent request context
452 * @return subject locality for the authentication statement
454 protected SubjectLocality buildSubjectLocality(SSORequestContext requestContext) {
455 HTTPInTransport transport = (HTTPInTransport) requestContext.getInboundMessageTransport();
456 SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
457 subjectLocality.setAddress(transport.getPeerAddress());
458 subjectLocality.setDNSName(transport.getPeerDomainName());
460 return subjectLocality;
464 * Selects the appropriate endpoint for the relying party and stores it in the request context.
466 * @param requestContext current request context
468 * @return Endpoint selected from the information provided in the request context
470 protected Endpoint selectEndpoint(SSORequestContext requestContext) {
471 AuthnResponseEndpointSelector endpointSelector = new AuthnResponseEndpointSelector();
472 endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
473 endpointSelector.setMetadataProvider(getMetadataProvider());
474 endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
475 endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
476 endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
477 endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
478 return endpointSelector.selectEndpoint();
481 /** Represents the internal state of a SAML 2.0 SSO Request while it's being processed by the IdP. */
482 protected class SSORequestContext extends BaseSAML2ProfileRequestContext<AuthnRequest, Response, SSOConfiguration> {
484 /** Current login context. */
485 private Saml2LoginContext loginContext;
488 * Gets the current login context.
490 * @return current login context
492 public Saml2LoginContext getLoginContext() {
497 * Sets the current login context.
499 * @param context current login context
501 public void setLoginContext(Saml2LoginContext context) {
502 loginContext = context;