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.core.SubjectLocality;
37 import org.opensaml.saml2.binding.AuthnResponseEndpointSelector;
38 import org.opensaml.saml2.core.AuthnContext;
39 import org.opensaml.saml2.core.AuthnContextClassRef;
40 import org.opensaml.saml2.core.AuthnContextDeclRef;
41 import org.opensaml.saml2.core.AuthnRequest;
42 import org.opensaml.saml2.core.AuthnStatement;
43 import org.opensaml.saml2.core.RequestedAuthnContext;
44 import org.opensaml.saml2.core.Response;
45 import org.opensaml.saml2.core.Statement;
46 import org.opensaml.saml2.core.StatusCode;
47 import org.opensaml.saml2.core.Subject;
48 import org.opensaml.saml2.metadata.AssertionConsumerService;
49 import org.opensaml.saml2.metadata.Endpoint;
50 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
51 import org.opensaml.ws.security.SecurityPolicyException;
52 import org.opensaml.xml.io.MarshallingException;
53 import org.opensaml.xml.io.UnmarshallingException;
55 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
56 import edu.internet2.middleware.shibboleth.common.profile.ProfileRequest;
57 import edu.internet2.middleware.shibboleth.common.profile.ProfileResponse;
58 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
59 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.SSOConfiguration;
60 import edu.internet2.middleware.shibboleth.common.util.HttpHelper;
61 import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
62 import edu.internet2.middleware.shibboleth.idp.authn.Saml2LoginContext;
64 /** SAML 2.0 SSO request profile handler. */
65 public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
68 private final Logger log = Logger.getLogger(SSOProfileHandler.class);
70 /** Builder of AuthnStatement objects. */
71 private SAMLObjectBuilder<AuthnStatement> authnStatementBuilder;
73 /** Builder of AuthnContext objects. */
74 private SAMLObjectBuilder<AuthnContext> authnContextBuilder;
76 /** Builder of AuthnContextClassRef objects. */
77 private SAMLObjectBuilder<AuthnContextClassRef> authnContextClassRefBuilder;
79 /** Builder of AuthnContextDeclRef objects. */
80 private SAMLObjectBuilder<AuthnContextDeclRef> authnContextDeclRefBuilder;
82 /** Builder of SubjectLocality objects. */
83 private SAMLObjectBuilder<SubjectLocality> subjectLocalityBuilder;
85 /** URL of the authentication manager servlet. */
86 private String authenticationManagerPath;
88 /** URI of request decoder. */
89 private String decodingBinding;
94 * @param authnManagerPath path to the authentication manager servlet
95 * @param decoder URI of the request decoder to use
97 @SuppressWarnings("unchecked")
98 public SSOProfileHandler(String authnManagerPath, String decoder) {
101 if (authnManagerPath == null || decoder == null) {
102 throw new IllegalArgumentException("AuthN manager path or decoding bindings URI may not be null");
105 authenticationManagerPath = authnManagerPath;
106 decodingBinding = decoder;
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(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response)
127 throws ProfileException {
129 HttpSession httpSession = ((HttpServletRequest) request.getRawRequest()).getSession(true);
130 if (httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY) == null) {
131 performAuthentication(request, response);
133 completeAuthenticationRequest(request, response);
138 * Creates a {@link Saml2LoginContext} an sends the request off to the AuthenticationManager to begin the process of
139 * authenticating the user.
141 * @param request current request
142 * @param response current response
144 * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
145 * authentication manager
147 protected void performAuthentication(ProfileRequest<ServletRequest> request,
148 ProfileResponse<ServletResponse> response) throws ProfileException {
149 HttpServletRequest httpRequest = (HttpServletRequest) request.getRawRequest();
151 AuthnRequest authnRequest = null;
153 MessageDecoder<ServletRequest> decoder = decodeRequest(request);
154 SAMLSecurityPolicy securityPolicy = decoder.getSecurityPolicy();
156 String relyingParty = securityPolicy.getIssuer();
157 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingParty);
158 if (rpConfig == null) {
159 log.error("No relying party configuration for " + relyingParty);
160 throw new ProfileException("No relying party configuration for " + relyingParty);
163 authnRequest = (AuthnRequest) decoder.getSAMLMessage();
165 Saml2LoginContext loginContext = new Saml2LoginContext(relyingParty, authnRequest);
166 loginContext.setAuthenticationEngineURL(authenticationManagerPath);
167 loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
168 if (loginContext.getRequestedAuthenticationMethods().size() == 0) {
169 loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
172 HttpSession httpSession = httpRequest.getSession();
173 httpSession.setAttribute(Saml2LoginContext.LOGIN_CONTEXT_KEY, loginContext);
174 RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
175 dispatcher.forward(httpRequest, response.getRawResponse());
176 } catch (MarshallingException e) {
177 log.error("Unable to marshall authentication request context");
178 throw new ProfileException("Unable to marshall authentication request context", e);
179 } catch (IOException ex) {
180 log.error("Error forwarding SAML 2 AuthnRequest " + authnRequest.getID() + " to AuthenticationManager", ex);
181 throw new ProfileException("Error forwarding SAML 2 AuthnRequest " + authnRequest.getID()
182 + " to AuthenticationManager", ex);
183 } catch (ServletException ex) {
184 log.error("Error forwarding SAML 2 AuthnRequest " + authnRequest.getID() + " to AuthenticationManager", ex);
185 throw new ProfileException("Error forwarding SAML 2 AuthnRequest " + authnRequest.getID()
186 + " to AuthenticationManager", ex);
191 * Creates a response to the {@link AuthnRequest} and sends the user, with response in tow, back to the relying
192 * party after they've been authenticated.
194 * @param request current request
195 * @param response current response
197 * @throws ProfileException thrown if the response can not be created and sent back to the relying party
199 protected void completeAuthenticationRequest(ProfileRequest<ServletRequest> request,
200 ProfileResponse<ServletResponse> response) throws ProfileException {
202 HttpSession httpSession = ((HttpServletRequest) request.getRawRequest()).getSession(true);
204 Saml2LoginContext loginContext = (Saml2LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
205 httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
207 SSORequestContext requestContext = buildRequestContext(loginContext, request, response);
209 checkSamlVersion(requestContext);
211 Response samlResponse;
213 if (!loginContext.isPrincipalAuthenticated()) {
215 .setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI, null));
216 throw new ProfileException("User failed authentication");
219 ArrayList<Statement> statements = new ArrayList<Statement>();
220 statements.add(buildAuthnStatement(requestContext));
221 if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
222 statements.add(buildAttributeStatement(requestContext));
225 Subject assertionSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:bearer");
227 samlResponse = buildResponse(requestContext, assertionSubject, statements);
228 } catch (ProfileException e) {
229 samlResponse = buildErrorResponse(requestContext);
232 requestContext.setSamlResponse(samlResponse);
233 encodeResponse(requestContext);
234 writeAuditLogEntry(requestContext);
238 * Creates an appropriate message decoder, populates it, and decodes the incoming request.
240 * @param request current request
242 * @return message decoder containing the decoded message and other stateful information
244 * @throws ProfileException thrown if the incomming message failed decoding
246 protected MessageDecoder<ServletRequest> decodeRequest(ProfileRequest<ServletRequest> request)
247 throws ProfileException {
248 MessageDecoder<ServletRequest> decoder = getMessageDecoderFactory().getMessageDecoder(decodingBinding);
249 if (decoder == null) {
250 log.error("No request decoder was registered for binding type: " + decodingBinding);
251 throw new ProfileException("No request decoder was registered for binding type: " + decodingBinding);
254 populateMessageDecoder(decoder);
255 decoder.setRequest(request.getRawRequest());
259 } catch (BindingException e) {
260 log.error("Error decoding authentication request message", e);
261 throw new ProfileException("Error decoding authentication request message", e);
262 } catch (SecurityPolicyException e) {
263 log.error("Message did not meet security policy requirements", e);
264 throw new ProfileException("Message did not meet security policy requirements", e);
269 * Creates an authentication request context from the current environmental information.
271 * @param loginContext current login context
272 * @param request current request
273 * @param response current response
275 * @return created authentication request context
277 * @throws ProfileException thrown if there is a problem creating the context
279 protected SSORequestContext buildRequestContext(Saml2LoginContext loginContext,
280 ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response) throws ProfileException {
281 SSORequestContext requestContext = new SSORequestContext(request, response);
284 requestContext.setMessageDecoder(getMessageDecoderFactory().getMessageDecoder(decodingBinding));
286 requestContext.setLoginContext(loginContext);
288 String relyingPartyId = loginContext.getRelyingPartyId();
289 AuthnRequest authnRequest = loginContext.getAuthenticationRequest();
291 requestContext.setRelyingPartyId(relyingPartyId);
293 requestContext.setRelyingPartyMetadata(getMetadataProvider().getEntityDescriptor(relyingPartyId));
295 requestContext.setRelyingPartyRoleMetadata(requestContext.getRelyingPartyMetadata().getSPSSODescriptor(
296 SAMLConstants.SAML20P_NS));
298 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
299 requestContext.setRelyingPartyConfiguration(rpConfig);
301 requestContext.setAssertingPartyId(requestContext.getRelyingPartyConfiguration().getProviderId());
303 requestContext.setAssertingPartyMetadata(getMetadataProvider().getEntityDescriptor(
304 requestContext.getAssertingPartyId()));
306 requestContext.setAssertingPartyRoleMetadata(requestContext.getRelyingPartyMetadata().getIDPSSODescriptor(
307 SAMLConstants.SAML20P_NS));
309 requestContext.setPrincipalName(loginContext.getPrincipalName());
311 requestContext.setProfileConfiguration((SSOConfiguration) rpConfig
312 .getProfileConfiguration(SSOConfiguration.PROFILE_ID));
314 requestContext.setSamlRequest(authnRequest);
316 return requestContext;
317 } catch (UnmarshallingException e) {
318 log.error("Unable to unmarshall authentication request context");
319 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
320 "Error recovering request state"));
321 throw new ProfileException("Error recovering request state", e);
322 } catch (MetadataProviderException e) {
323 log.error("Unable to locate metadata for asserting or relying party");
325 .setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error locating party metadata"));
326 throw new ProfileException("Error locating party metadata");
331 * Creates an authentication statement for the current request.
333 * @param requestContext current request context
335 * @return constructed authentication statement
337 protected AuthnStatement buildAuthnStatement(SSORequestContext requestContext) {
338 Saml2LoginContext loginContext = requestContext.getLoginContext();
340 AuthnContext authnContext = buildAuthnContext(requestContext);
342 AuthnStatement statement = authnStatementBuilder.buildObject();
343 statement.setAuthnContext(authnContext);
344 statement.setAuthnInstant(loginContext.getAuthenticationInstant());
347 statement.setSessionIndex(null);
349 if (loginContext.getAuthenticationDuration() > 0) {
350 statement.setSessionNotOnOrAfter(loginContext.getAuthenticationInstant().plus(
351 loginContext.getAuthenticationDuration()));
354 statement.setSubjectLocality(buildSubjectLocality(requestContext));
360 * Creates an {@link AuthnContext} for a succesful authentication request.
362 * @param requestContext current request
364 * @return the built authn context
366 protected AuthnContext buildAuthnContext(SSORequestContext requestContext) {
367 AuthnContext authnContext = authnContextBuilder.buildObject();
369 Saml2LoginContext loginContext = requestContext.getLoginContext();
370 AuthnRequest authnRequest = requestContext.getSamlRequest();
371 RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
372 if (requestedAuthnContext != null) {
373 if (requestedAuthnContext.getAuthnContextClassRefs() != null) {
374 for (AuthnContextClassRef classRef : requestedAuthnContext.getAuthnContextClassRefs()) {
375 if (classRef.getAuthnContextClassRef().equals(loginContext.getAuthenticationMethod())) {
376 AuthnContextClassRef ref = authnContextClassRefBuilder.buildObject();
377 ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
378 authnContext.setAuthnContextClassRef(ref);
381 } else if (requestedAuthnContext.getAuthnContextDeclRefs() != null) {
382 for (AuthnContextDeclRef declRef : requestedAuthnContext.getAuthnContextDeclRefs()) {
383 if (declRef.getAuthnContextDeclRef().equals(loginContext.getAuthenticationMethod())) {
384 AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
385 ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
386 authnContext.setAuthnContextDeclRef(ref);
391 AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
392 ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
393 authnContext.setAuthnContextDeclRef(ref);
400 * Constructs the subject locality for the authentication statement.
402 * @param requestContext curent request context
404 * @return subject locality for the authentication statement
406 protected SubjectLocality buildSubjectLocality(SSORequestContext requestContext) {
407 SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
409 HttpServletRequest httpRequest = (HttpServletRequest) requestContext.getProfileRequest().getRawRequest();
410 subjectLocality.setAddress(httpRequest.getRemoteAddr());
411 subjectLocality.setDNSName(httpRequest.getRemoteHost());
413 return subjectLocality;
417 * Encodes the request's SAML response and writes it to the servlet response.
419 * @param requestContext current request context
421 * @throws ProfileException thrown if no message encoder is registered for this profiles binding
423 protected void encodeResponse(SSORequestContext requestContext) throws ProfileException {
424 if (log.isDebugEnabled()) {
425 log.debug("Encoding response to SAML request " + requestContext.getSamlRequest().getID()
426 + " from relying party " + requestContext.getRelyingPartyId());
428 AuthnResponseEndpointSelector endpointSelector = new AuthnResponseEndpointSelector();
429 endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
430 endpointSelector.setMetadataProvider(getMetadataProvider());
431 endpointSelector.setRelyingParty(requestContext.getRelyingPartyMetadata());
432 endpointSelector.setRelyingPartyRole(requestContext.getRelyingPartyRoleMetadata());
433 endpointSelector.setSamlRequest(requestContext.getSamlRequest());
434 endpointSelector.getSupportedIssuerBindings().addAll(getMessageEncoderFactory().getEncoderBuilders().keySet());
435 Endpoint relyingPartyEndpoint = endpointSelector.selectEndpoint();
437 MessageEncoder<ServletResponse> encoder = getMessageEncoderFactory().getMessageEncoder(
438 relyingPartyEndpoint.getBinding());
439 if (encoder == null) {
440 log.error("No response encoder was registered for binding type: " + relyingPartyEndpoint.getBinding());
441 throw new ProfileException("No response encoder was registered for binding type: "
442 + relyingPartyEndpoint.getBinding());
445 super.populateMessageEncoder(encoder);
446 encoder.setIssuer(requestContext.getAssertingPartyId());
447 encoder.setRelyingParty(requestContext.getRelyingPartyMetadata());
448 encoder.setRelyingPartyEndpoint(relyingPartyEndpoint);
449 encoder.setRelyingPartyRole(requestContext.getRelyingPartyRoleMetadata());
450 ProfileResponse<ServletResponse> profileResponse = requestContext.getProfileResponse();
451 encoder.setResponse(profileResponse.getRawResponse());
452 encoder.setSamlMessage(requestContext.getSamlResponse());
453 requestContext.setMessageEncoder(encoder);
457 } catch (BindingException e) {
458 throw new ProfileException("Unable to encode response to relying party: "
459 + requestContext.getRelyingPartyId(), e);
463 /** Represents the internal state of a SAML 2.0 SSO Request while it's being processed by the IdP. */
464 protected class SSORequestContext extends SAML2ProfileRequestContext<AuthnRequest, Response, SSOConfiguration> {
466 /** Current login context. */
467 private Saml2LoginContext loginContext;
472 * @param request current profile request
473 * @param response current profile response
475 public SSORequestContext(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response) {
476 super(request, response);
480 * Gets the current login context.
482 * @return current login context
484 public Saml2LoginContext getLoginContext() {
489 * Sets the current login context.
491 * @param context current login context
493 public void setLoginContext(Saml2LoginContext context) {
494 loginContext = context;