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.ServletRequest;
25 import javax.servlet.ServletResponse;
26 import javax.servlet.http.HttpServletRequest;
27 import javax.servlet.http.HttpSession;
29 import org.apache.log4j.Logger;
30 import org.opensaml.common.SAMLObjectBuilder;
31 import org.opensaml.common.binding.BindingException;
32 import org.opensaml.common.binding.decoding.MessageDecoder;
33 import org.opensaml.common.binding.encoding.MessageEncoder;
34 import org.opensaml.common.binding.security.SAMLSecurityPolicy;
35 import org.opensaml.common.xml.SAMLConstants;
36 import org.opensaml.saml2.binding.AuthnResponseEndpointSelector;
37 import org.opensaml.saml2.core.AuthnContext;
38 import org.opensaml.saml2.core.AuthnContextClassRef;
39 import org.opensaml.saml2.core.AuthnContextDeclRef;
40 import org.opensaml.saml2.core.AuthnRequest;
41 import org.opensaml.saml2.core.AuthnStatement;
42 import org.opensaml.saml2.core.RequestedAuthnContext;
43 import org.opensaml.saml2.core.Response;
44 import org.opensaml.saml2.core.Statement;
45 import org.opensaml.saml2.core.StatusCode;
46 import org.opensaml.saml2.core.Subject;
47 import org.opensaml.saml2.metadata.AssertionConsumerService;
48 import org.opensaml.saml2.metadata.Endpoint;
49 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
50 import org.opensaml.ws.security.SecurityPolicyException;
51 import org.opensaml.xml.io.MarshallingException;
52 import org.opensaml.xml.io.UnmarshallingException;
54 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
55 import edu.internet2.middleware.shibboleth.common.profile.ProfileRequest;
56 import edu.internet2.middleware.shibboleth.common.profile.ProfileResponse;
57 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
58 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.SSOConfiguration;
59 import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
60 import edu.internet2.middleware.shibboleth.idp.authn.Saml2LoginContext;
62 /** SAML 2.0 SSO request profile handler. */
63 public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
66 private final Logger log = Logger.getLogger(SSOProfileHandler.class);
68 /** Builder of AuthnStatement objects. */
69 private SAMLObjectBuilder<AuthnStatement> authnStatementBuilder;
71 /** Builder of AuthnContext objects. */
72 private SAMLObjectBuilder<AuthnContext> authnContextBuilder;
74 /** Builder of AuthnContextClassRef objects. */
75 private SAMLObjectBuilder<AuthnContextClassRef> authnContextClassRefBuilder;
77 /** Builder of AuthnContextDeclRef objects. */
78 private SAMLObjectBuilder<AuthnContextDeclRef> authnContextDeclRefBuilder;
80 /** URL of the authentication manager servlet. */
81 private String authenticationManagerPath;
83 /** URI of request decoder. */
84 private String decodingBinding;
89 * @param authnManagerPath path to the authentication manager servlet
90 * @param decoder URI of the request decoder to use
92 @SuppressWarnings("unchecked")
93 public SSOProfileHandler(String authnManagerPath, String decoder) {
96 if (authnManagerPath == null || decoder == null) {
97 throw new IllegalArgumentException("AuthN manager path or decoding bindings URI may not be null");
100 authenticationManagerPath = authnManagerPath;
101 decodingBinding = decoder;
103 authnStatementBuilder = (SAMLObjectBuilder<AuthnStatement>) getBuilderFactory().getBuilder(
104 AuthnStatement.DEFAULT_ELEMENT_NAME);
105 authnContextBuilder = (SAMLObjectBuilder<AuthnContext>) getBuilderFactory().getBuilder(
106 AuthnContext.DEFAULT_ELEMENT_NAME);
107 authnContextClassRefBuilder = (SAMLObjectBuilder<AuthnContextClassRef>) getBuilderFactory().getBuilder(
108 AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
109 authnContextDeclRefBuilder = (SAMLObjectBuilder<AuthnContextDeclRef>) getBuilderFactory().getBuilder(
110 AuthnContextDeclRef.DEFAULT_ELEMENT_NAME);
114 * Convenience method for getting the SAML 2 AuthnStatement builder.
116 * @return SAML 2 AuthnStatement builder
118 public SAMLObjectBuilder<AuthnStatement> getAuthnStatementBuilder() {
119 return authnStatementBuilder;
123 * Convenience method for getting the SAML 2 AuthnContext builder.
125 * @return SAML 2 AuthnContext builder
127 public SAMLObjectBuilder<AuthnContext> getAuthnContextBuilder() {
128 return authnContextBuilder;
132 * Convenience method for getting the SAML 2 AuthnContextClassRef builder.
134 * @return SAML 2 AuthnContextClassRef builder
136 public SAMLObjectBuilder<AuthnContextClassRef> getAuthnContextClassRefBuilder() {
137 return authnContextClassRefBuilder;
141 * Convenience method for getting the SAML 2 AuthnContextDeclRef builder.
143 * @return SAML 2 AuthnContextDeclRef builder
145 public SAMLObjectBuilder<AuthnContextDeclRef> getAuthnContextDeclRefBuilder() {
146 return authnContextDeclRefBuilder;
150 public String getProfileId() {
151 return "urn:mace:shibboleth:2.0:idp:profiles:saml2:request:sso";
155 public void processRequest(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response)
156 throws ProfileException {
158 HttpSession httpSession = ((HttpServletRequest) request.getRawRequest()).getSession(true);
159 if (httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY) == null) {
160 performAuthentication(request, response);
162 completeAuthenticationRequest(request, response);
167 * Creates a {@link Saml2LoginContext} an sends the request off to the AuthenticationManager to begin the process of
168 * authenticating the user.
170 * @param request current request
171 * @param response current response
173 * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
174 * authentication manager
176 protected void performAuthentication(ProfileRequest<ServletRequest> request,
177 ProfileResponse<ServletResponse> response) throws ProfileException {
178 HttpServletRequest httpRequest = (HttpServletRequest) request.getRawRequest();
180 AuthnRequest authnRequest = null;
182 MessageDecoder<ServletRequest> decoder = decodeRequest(request);
183 SAMLSecurityPolicy securityPolicy = decoder.getSecurityPolicy();
185 String relyingParty = securityPolicy.getIssuer();
186 authnRequest = (AuthnRequest) decoder.getSAMLMessage();
188 Saml2LoginContext loginContext = new Saml2LoginContext(relyingParty, authnRequest);
189 loginContext.setAuthenticationEngineURL(authenticationManagerPath);
190 loginContext.setProfileHandlerURL(httpRequest.getRequestURI());
192 HttpSession httpSession = httpRequest.getSession();
193 httpSession.setAttribute(Saml2LoginContext.LOGIN_CONTEXT_KEY, loginContext);
194 RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
195 dispatcher.forward(httpRequest, response.getRawResponse());
196 } catch (MarshallingException e) {
197 log.error("Unable to marshall authentication request context");
198 throw new ProfileException("Unable to marshall authentication request context", e);
199 } catch (IOException ex) {
200 log.error("Error forwarding SAML 2 AuthnRequest " + authnRequest.getID() + " to AuthenticationManager", ex);
201 throw new ProfileException("Error forwarding SAML 2 AuthnRequest " + authnRequest.getID()
202 + " to AuthenticationManager", ex);
203 } catch (ServletException ex) {
204 log.error("Error forwarding SAML 2 AuthnRequest " + authnRequest.getID() + " to AuthenticationManager", ex);
205 throw new ProfileException("Error forwarding SAML 2 AuthnRequest " + authnRequest.getID()
206 + " to AuthenticationManager", ex);
211 * Creates a response to the {@link AuthnRequest} and sends the user, with response in tow, back to the relying
212 * party after they've been authenticated.
214 * @param request current request
215 * @param response current response
217 * @throws ProfileException thrown if the response can not be created and sent back to the relying party
219 protected void completeAuthenticationRequest(ProfileRequest<ServletRequest> request,
220 ProfileResponse<ServletResponse> response) throws ProfileException {
222 HttpSession httpSession = ((HttpServletRequest) request.getRawRequest()).getSession(true);
224 Saml2LoginContext loginContext = (Saml2LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
225 httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
227 SSORequestContext requestContext = buildRequestContext(loginContext, request, response);
229 checkSamlVersion(requestContext);
231 Response samlResponse;
233 if (!loginContext.isPrincipalAuthenticated()) {
235 .setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI, null));
236 throw new ProfileException("User failed authentication");
239 ArrayList<Statement> statements = new ArrayList<Statement>();
240 statements.add(buildAuthnStatement(requestContext));
241 if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
242 statements.add(buildAttributeStatement(requestContext));
245 Subject assertionSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:bearer");
247 samlResponse = buildResponse(requestContext, assertionSubject, statements);
248 } catch (ProfileException e) {
249 samlResponse = buildErrorResponse(requestContext);
252 requestContext.setSamlResponse(samlResponse);
253 encodeResponse(requestContext);
254 writeAuditLogEntry(requestContext);
258 * Creates an appropriate message decoder, populates it, and decodes the incoming request.
260 * @param request current request
262 * @return message decoder containing the decoded message and other stateful information
264 * @throws ProfileException thrown if the incomming message failed decoding
266 protected MessageDecoder<ServletRequest> decodeRequest(ProfileRequest<ServletRequest> request)
267 throws ProfileException {
268 MessageDecoder<ServletRequest> decoder = getMessageDecoderFactory().getMessageDecoder(decodingBinding);
269 if (decoder == null) {
270 log.error("No request decoder was registered for binding type: " + decodingBinding);
271 throw new ProfileException("No request decoder was registered for binding type: " + decodingBinding);
274 populateMessageDecoder(decoder);
275 decoder.setRequest(request.getRawRequest());
279 } catch (BindingException e) {
280 log.error("Error decoding authentication request message", e);
281 throw new ProfileException("Error decoding authentication request message", e);
282 } catch (SecurityPolicyException e) {
283 log.error("Message did not meet security policy requirements", e);
284 throw new ProfileException("Message did not meet security policy requirements", e);
289 * Creates an authentication request context from the current environmental information.
291 * @param loginContext current login context
292 * @param request current request
293 * @param response current response
295 * @return created authentication request context
297 * @throws ProfileException thrown if there is a problem creating the context
299 protected SSORequestContext buildRequestContext(Saml2LoginContext loginContext,
300 ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response) throws ProfileException {
301 SSORequestContext requestContext = new SSORequestContext(request, response);
304 requestContext.setMessageDecoder(getMessageDecoderFactory().getMessageDecoder(decodingBinding));
306 requestContext.setLoginContext(loginContext);
308 String relyingPartyId = loginContext.getRelyingPartyId();
309 AuthnRequest authnRequest = loginContext.getAuthenticationRequest();
311 requestContext.setRelyingPartyId(relyingPartyId);
313 requestContext.setRelyingPartyMetadata(getMetadataProvider().getEntityDescriptor(relyingPartyId));
315 requestContext.setRelyingPartyRoleMetadata(requestContext.getRelyingPartyMetadata().getSPSSODescriptor(
316 SAMLConstants.SAML20P_NS));
318 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
319 requestContext.setRelyingPartyConfiguration(rpConfig);
321 requestContext.setAssertingPartyId(requestContext.getRelyingPartyConfiguration().getProviderId());
323 requestContext.setAssertingPartyMetadata(getMetadataProvider().getEntityDescriptor(
324 requestContext.getAssertingPartyId()));
326 requestContext.setAssertingPartyRoleMetadata(requestContext.getRelyingPartyMetadata().getIDPSSODescriptor(
327 SAMLConstants.SAML20P_NS));
329 requestContext.setPrincipalName(loginContext.getPrincipalName());
331 requestContext.setProfileConfiguration((SSOConfiguration) rpConfig
332 .getProfileConfiguration(SSOConfiguration.PROFILE_ID));
334 requestContext.setSamlRequest(authnRequest);
336 return requestContext;
337 } catch (UnmarshallingException e) {
338 log.error("Unable to unmarshall authentication request context");
339 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
340 "Error recovering request state"));
341 throw new ProfileException("Error recovering request state", e);
342 } catch (MetadataProviderException e) {
343 log.error("Unable to locate metadata for asserting or relying party");
345 .setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error locating party metadata"));
346 throw new ProfileException("Error locating party metadata");
351 * Creates an authentication statement for the current request.
353 * @param requestContext current request context
355 * @return constructed authentication statement
357 protected AuthnStatement buildAuthnStatement(SSORequestContext requestContext) {
358 Saml2LoginContext loginContext = requestContext.getLoginContext();
360 AuthnContext authnContext = buildAuthnContext(requestContext);
362 AuthnStatement statement = getAuthnStatementBuilder().buildObject();
363 statement.setAuthnContext(authnContext);
364 statement.setAuthnInstant(loginContext.getAuthenticationInstant());
367 statement.setSessionIndex(null);
369 if (loginContext.getAuthenticationDuration() > 0) {
370 statement.setSessionNotOnOrAfter(loginContext.getAuthenticationInstant().plus(
371 loginContext.getAuthenticationDuration()));
375 statement.setSubjectLocality(null);
381 * Creates an {@link AuthnContext} for a succesful authentication request.
383 * @param requestContext current request
385 * @return the built authn context
387 protected AuthnContext buildAuthnContext(SSORequestContext requestContext) {
388 AuthnContext authnContext = getAuthnContextBuilder().buildObject();
390 Saml2LoginContext loginContext = requestContext.getLoginContext();
391 AuthnRequest authnRequest = requestContext.getSamlRequest();
392 RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
393 if (requestedAuthnContext != null) {
394 if (requestedAuthnContext.getAuthnContextClassRefs() != null) {
395 for (AuthnContextClassRef classRef : requestedAuthnContext.getAuthnContextClassRefs()) {
396 if (classRef.getAuthnContextClassRef().equals(loginContext.getAuthenticationMethod())) {
397 AuthnContextClassRef ref = getAuthnContextClassRefBuilder().buildObject();
398 ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
399 authnContext.setAuthnContextClassRef(ref);
402 } else if (requestedAuthnContext.getAuthnContextDeclRefs() != null) {
403 for (AuthnContextDeclRef declRef : requestedAuthnContext.getAuthnContextDeclRefs()) {
404 if (declRef.getAuthnContextDeclRef().equals(loginContext.getAuthenticationMethod())) {
405 AuthnContextDeclRef ref = getAuthnContextDeclRefBuilder().buildObject();
406 ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
407 authnContext.setAuthnContextDeclRef(ref);
412 AuthnContextDeclRef ref = getAuthnContextDeclRefBuilder().buildObject();
413 ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
414 authnContext.setAuthnContextDeclRef(ref);
421 * Encodes the request's SAML response and writes it to the servlet response.
423 * @param requestContext current request context
425 * @throws ProfileException thrown if no message encoder is registered for this profiles binding
427 protected void encodeResponse(SSORequestContext requestContext) throws ProfileException {
428 if (log.isDebugEnabled()) {
429 log.debug("Encoding response to SAML request " + requestContext.getSamlRequest().getID()
430 + " from relying party " + requestContext.getRelyingPartyId());
432 AuthnResponseEndpointSelector endpointSelector = new AuthnResponseEndpointSelector();
433 endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
434 endpointSelector.setMetadataProvider(getMetadataProvider());
435 endpointSelector.setRelyingParty(requestContext.getRelyingPartyMetadata());
436 endpointSelector.setRelyingPartyRole(requestContext.getRelyingPartyRoleMetadata());
437 endpointSelector.setSamlRequest(requestContext.getSamlRequest());
438 endpointSelector.getSupportedIssuerBindings().addAll(getMessageEncoderFactory().getEncoderBuilders().keySet());
439 Endpoint relyingPartyEndpoint = endpointSelector.selectEndpoint();
441 MessageEncoder<ServletResponse> encoder = getMessageEncoderFactory().getMessageEncoder(
442 relyingPartyEndpoint.getBinding());
443 if (encoder == null) {
444 log.error("No response encoder was registered for binding type: " + relyingPartyEndpoint.getBinding());
445 throw new ProfileException("No response encoder was registered for binding type: "
446 + relyingPartyEndpoint.getBinding());
449 super.populateMessageEncoder(encoder);
450 encoder.setIssuer(requestContext.getAssertingPartyId());
451 encoder.setRelyingParty(requestContext.getRelyingPartyMetadata());
452 encoder.setRelyingPartyEndpoint(relyingPartyEndpoint);
453 encoder.setRelyingPartyRole(requestContext.getRelyingPartyRoleMetadata());
454 encoder.setResponse(requestContext.getProfileResponse().getRawResponse());
455 encoder.setSamlMessage(requestContext.getSamlResponse());
456 requestContext.setMessageEncoder(encoder);
460 } catch (BindingException e) {
461 throw new ProfileException("Unable to encode response to relying party: "
462 + requestContext.getRelyingPartyId(), e);
466 /** Represents the internal state of a SAML 2.0 SSO Request while it's being processed by the IdP. */
467 protected class SSORequestContext extends SAML2ProfileRequestContext<AuthnRequest, Response, SSOConfiguration> {
469 /** Current login context. */
470 private Saml2LoginContext loginContext;
475 * @param request current profile request
476 * @param response current profile response
478 public SSORequestContext(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response) {
479 super(request, response);
483 * Gets the current login context.
485 * @return current login context
487 public Saml2LoginContext getLoginContext() {
492 * Sets the current login context.
494 * @param context current login context
496 public void setLoginContext(Saml2LoginContext context) {
497 loginContext = context;