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.common.util.HttpHelper;
60 import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
61 import edu.internet2.middleware.shibboleth.idp.authn.Saml2LoginContext;
63 /** SAML 2.0 SSO request profile handler. */
64 public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
67 private final Logger log = Logger.getLogger(SSOProfileHandler.class);
69 /** Builder of AuthnStatement objects. */
70 private SAMLObjectBuilder<AuthnStatement> authnStatementBuilder;
72 /** Builder of AuthnContext objects. */
73 private SAMLObjectBuilder<AuthnContext> authnContextBuilder;
75 /** Builder of AuthnContextClassRef objects. */
76 private SAMLObjectBuilder<AuthnContextClassRef> authnContextClassRefBuilder;
78 /** Builder of AuthnContextDeclRef objects. */
79 private SAMLObjectBuilder<AuthnContextDeclRef> authnContextDeclRefBuilder;
81 /** URL of the authentication manager servlet. */
82 private String authenticationManagerPath;
84 /** URI of request decoder. */
85 private String decodingBinding;
90 * @param authnManagerPath path to the authentication manager servlet
91 * @param decoder URI of the request decoder to use
93 @SuppressWarnings("unchecked")
94 public SSOProfileHandler(String authnManagerPath, String decoder) {
97 if (authnManagerPath == null || decoder == null) {
98 throw new IllegalArgumentException("AuthN manager path or decoding bindings URI may not be null");
101 authenticationManagerPath = authnManagerPath;
102 decodingBinding = decoder;
104 authnStatementBuilder = (SAMLObjectBuilder<AuthnStatement>) getBuilderFactory().getBuilder(
105 AuthnStatement.DEFAULT_ELEMENT_NAME);
106 authnContextBuilder = (SAMLObjectBuilder<AuthnContext>) getBuilderFactory().getBuilder(
107 AuthnContext.DEFAULT_ELEMENT_NAME);
108 authnContextClassRefBuilder = (SAMLObjectBuilder<AuthnContextClassRef>) getBuilderFactory().getBuilder(
109 AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
110 authnContextDeclRefBuilder = (SAMLObjectBuilder<AuthnContextDeclRef>) getBuilderFactory().getBuilder(
111 AuthnContextDeclRef.DEFAULT_ELEMENT_NAME);
115 * Convenience method for getting the SAML 2 AuthnStatement builder.
117 * @return SAML 2 AuthnStatement builder
119 public SAMLObjectBuilder<AuthnStatement> getAuthnStatementBuilder() {
120 return authnStatementBuilder;
124 * Convenience method for getting the SAML 2 AuthnContext builder.
126 * @return SAML 2 AuthnContext builder
128 public SAMLObjectBuilder<AuthnContext> getAuthnContextBuilder() {
129 return authnContextBuilder;
133 * Convenience method for getting the SAML 2 AuthnContextClassRef builder.
135 * @return SAML 2 AuthnContextClassRef builder
137 public SAMLObjectBuilder<AuthnContextClassRef> getAuthnContextClassRefBuilder() {
138 return authnContextClassRefBuilder;
142 * Convenience method for getting the SAML 2 AuthnContextDeclRef builder.
144 * @return SAML 2 AuthnContextDeclRef builder
146 public SAMLObjectBuilder<AuthnContextDeclRef> getAuthnContextDeclRefBuilder() {
147 return authnContextDeclRefBuilder;
151 public String getProfileId() {
152 return "urn:mace:shibboleth:2.0:idp:profiles:saml2:request:sso";
156 public void processRequest(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response)
157 throws ProfileException {
159 HttpSession httpSession = ((HttpServletRequest) request.getRawRequest()).getSession(true);
160 if (httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY) == null) {
161 performAuthentication(request, response);
163 completeAuthenticationRequest(request, response);
168 * Creates a {@link Saml2LoginContext} an sends the request off to the AuthenticationManager to begin the process of
169 * authenticating the user.
171 * @param request current request
172 * @param response current response
174 * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
175 * authentication manager
177 protected void performAuthentication(ProfileRequest<ServletRequest> request,
178 ProfileResponse<ServletResponse> response) throws ProfileException {
179 HttpServletRequest httpRequest = (HttpServletRequest) request.getRawRequest();
181 AuthnRequest authnRequest = null;
183 MessageDecoder<ServletRequest> decoder = decodeRequest(request);
184 SAMLSecurityPolicy securityPolicy = decoder.getSecurityPolicy();
186 String relyingParty = securityPolicy.getIssuer();
187 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingParty);
188 if(rpConfig == null){
189 log.error("No relying party configuration for " + relyingParty);
190 throw new ProfileException("No relying party configuration for " + relyingParty);
193 authnRequest = (AuthnRequest) decoder.getSAMLMessage();
195 Saml2LoginContext loginContext = new Saml2LoginContext(relyingParty, authnRequest);
196 loginContext.setAuthenticationEngineURL(authenticationManagerPath);
197 loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
198 if (loginContext.getRequestedAuthenticationMethods().size() == 0) {
199 loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
202 HttpSession httpSession = httpRequest.getSession();
203 httpSession.setAttribute(Saml2LoginContext.LOGIN_CONTEXT_KEY, loginContext);
204 RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
205 dispatcher.forward(httpRequest, response.getRawResponse());
206 } catch (MarshallingException e) {
207 log.error("Unable to marshall authentication request context");
208 throw new ProfileException("Unable to marshall authentication request context", e);
209 } catch (IOException ex) {
210 log.error("Error forwarding SAML 2 AuthnRequest " + authnRequest.getID() + " to AuthenticationManager", ex);
211 throw new ProfileException("Error forwarding SAML 2 AuthnRequest " + authnRequest.getID()
212 + " to AuthenticationManager", ex);
213 } catch (ServletException ex) {
214 log.error("Error forwarding SAML 2 AuthnRequest " + authnRequest.getID() + " to AuthenticationManager", ex);
215 throw new ProfileException("Error forwarding SAML 2 AuthnRequest " + authnRequest.getID()
216 + " to AuthenticationManager", ex);
221 * Creates a response to the {@link AuthnRequest} and sends the user, with response in tow, back to the relying
222 * party after they've been authenticated.
224 * @param request current request
225 * @param response current response
227 * @throws ProfileException thrown if the response can not be created and sent back to the relying party
229 protected void completeAuthenticationRequest(ProfileRequest<ServletRequest> request,
230 ProfileResponse<ServletResponse> response) throws ProfileException {
232 HttpSession httpSession = ((HttpServletRequest) request.getRawRequest()).getSession(true);
234 Saml2LoginContext loginContext = (Saml2LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
235 httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
237 SSORequestContext requestContext = buildRequestContext(loginContext, request, response);
239 checkSamlVersion(requestContext);
241 Response samlResponse;
243 if (!loginContext.isPrincipalAuthenticated()) {
245 .setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI, null));
246 throw new ProfileException("User failed authentication");
249 ArrayList<Statement> statements = new ArrayList<Statement>();
250 statements.add(buildAuthnStatement(requestContext));
251 if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
252 statements.add(buildAttributeStatement(requestContext));
255 Subject assertionSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:bearer");
257 samlResponse = buildResponse(requestContext, assertionSubject, statements);
258 } catch (ProfileException e) {
259 samlResponse = buildErrorResponse(requestContext);
262 requestContext.setSamlResponse(samlResponse);
263 encodeResponse(requestContext);
264 writeAuditLogEntry(requestContext);
268 * Creates an appropriate message decoder, populates it, and decodes the incoming request.
270 * @param request current request
272 * @return message decoder containing the decoded message and other stateful information
274 * @throws ProfileException thrown if the incomming message failed decoding
276 protected MessageDecoder<ServletRequest> decodeRequest(ProfileRequest<ServletRequest> request)
277 throws ProfileException {
278 MessageDecoder<ServletRequest> decoder = getMessageDecoderFactory().getMessageDecoder(decodingBinding);
279 if (decoder == null) {
280 log.error("No request decoder was registered for binding type: " + decodingBinding);
281 throw new ProfileException("No request decoder was registered for binding type: " + decodingBinding);
284 populateMessageDecoder(decoder);
285 decoder.setRequest(request.getRawRequest());
289 } catch (BindingException e) {
290 log.error("Error decoding authentication request message", e);
291 throw new ProfileException("Error decoding authentication request message", e);
292 } catch (SecurityPolicyException e) {
293 log.error("Message did not meet security policy requirements", e);
294 throw new ProfileException("Message did not meet security policy requirements", e);
299 * Creates an authentication request context from the current environmental information.
301 * @param loginContext current login context
302 * @param request current request
303 * @param response current response
305 * @return created authentication request context
307 * @throws ProfileException thrown if there is a problem creating the context
309 protected SSORequestContext buildRequestContext(Saml2LoginContext loginContext,
310 ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response) throws ProfileException {
311 SSORequestContext requestContext = new SSORequestContext(request, response);
314 requestContext.setMessageDecoder(getMessageDecoderFactory().getMessageDecoder(decodingBinding));
316 requestContext.setLoginContext(loginContext);
318 String relyingPartyId = loginContext.getRelyingPartyId();
319 AuthnRequest authnRequest = loginContext.getAuthenticationRequest();
321 requestContext.setRelyingPartyId(relyingPartyId);
323 requestContext.setRelyingPartyMetadata(getMetadataProvider().getEntityDescriptor(relyingPartyId));
325 requestContext.setRelyingPartyRoleMetadata(requestContext.getRelyingPartyMetadata().getSPSSODescriptor(
326 SAMLConstants.SAML20P_NS));
328 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
329 requestContext.setRelyingPartyConfiguration(rpConfig);
331 requestContext.setAssertingPartyId(requestContext.getRelyingPartyConfiguration().getProviderId());
333 requestContext.setAssertingPartyMetadata(getMetadataProvider().getEntityDescriptor(
334 requestContext.getAssertingPartyId()));
336 requestContext.setAssertingPartyRoleMetadata(requestContext.getRelyingPartyMetadata().getIDPSSODescriptor(
337 SAMLConstants.SAML20P_NS));
339 requestContext.setPrincipalName(loginContext.getPrincipalName());
341 requestContext.setProfileConfiguration((SSOConfiguration) rpConfig
342 .getProfileConfiguration(SSOConfiguration.PROFILE_ID));
344 requestContext.setSamlRequest(authnRequest);
346 return requestContext;
347 } catch (UnmarshallingException e) {
348 log.error("Unable to unmarshall authentication request context");
349 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
350 "Error recovering request state"));
351 throw new ProfileException("Error recovering request state", e);
352 } catch (MetadataProviderException e) {
353 log.error("Unable to locate metadata for asserting or relying party");
355 .setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error locating party metadata"));
356 throw new ProfileException("Error locating party metadata");
361 * Creates an authentication statement for the current request.
363 * @param requestContext current request context
365 * @return constructed authentication statement
367 protected AuthnStatement buildAuthnStatement(SSORequestContext requestContext) {
368 Saml2LoginContext loginContext = requestContext.getLoginContext();
370 AuthnContext authnContext = buildAuthnContext(requestContext);
372 AuthnStatement statement = getAuthnStatementBuilder().buildObject();
373 statement.setAuthnContext(authnContext);
374 statement.setAuthnInstant(loginContext.getAuthenticationInstant());
377 statement.setSessionIndex(null);
379 if (loginContext.getAuthenticationDuration() > 0) {
380 statement.setSessionNotOnOrAfter(loginContext.getAuthenticationInstant().plus(
381 loginContext.getAuthenticationDuration()));
385 statement.setSubjectLocality(null);
391 * Creates an {@link AuthnContext} for a succesful authentication request.
393 * @param requestContext current request
395 * @return the built authn context
397 protected AuthnContext buildAuthnContext(SSORequestContext requestContext) {
398 AuthnContext authnContext = getAuthnContextBuilder().buildObject();
400 Saml2LoginContext loginContext = requestContext.getLoginContext();
401 AuthnRequest authnRequest = requestContext.getSamlRequest();
402 RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
403 if (requestedAuthnContext != null) {
404 if (requestedAuthnContext.getAuthnContextClassRefs() != null) {
405 for (AuthnContextClassRef classRef : requestedAuthnContext.getAuthnContextClassRefs()) {
406 if (classRef.getAuthnContextClassRef().equals(loginContext.getAuthenticationMethod())) {
407 AuthnContextClassRef ref = getAuthnContextClassRefBuilder().buildObject();
408 ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
409 authnContext.setAuthnContextClassRef(ref);
412 } else if (requestedAuthnContext.getAuthnContextDeclRefs() != null) {
413 for (AuthnContextDeclRef declRef : requestedAuthnContext.getAuthnContextDeclRefs()) {
414 if (declRef.getAuthnContextDeclRef().equals(loginContext.getAuthenticationMethod())) {
415 AuthnContextDeclRef ref = getAuthnContextDeclRefBuilder().buildObject();
416 ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
417 authnContext.setAuthnContextDeclRef(ref);
422 AuthnContextDeclRef ref = getAuthnContextDeclRefBuilder().buildObject();
423 ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
424 authnContext.setAuthnContextDeclRef(ref);
431 * Encodes the request's SAML response and writes it to the servlet response.
433 * @param requestContext current request context
435 * @throws ProfileException thrown if no message encoder is registered for this profiles binding
437 protected void encodeResponse(SSORequestContext requestContext) throws ProfileException {
438 if (log.isDebugEnabled()) {
439 log.debug("Encoding response to SAML request " + requestContext.getSamlRequest().getID()
440 + " from relying party " + requestContext.getRelyingPartyId());
442 AuthnResponseEndpointSelector endpointSelector = new AuthnResponseEndpointSelector();
443 endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
444 endpointSelector.setMetadataProvider(getMetadataProvider());
445 endpointSelector.setRelyingParty(requestContext.getRelyingPartyMetadata());
446 endpointSelector.setRelyingPartyRole(requestContext.getRelyingPartyRoleMetadata());
447 endpointSelector.setSamlRequest(requestContext.getSamlRequest());
448 endpointSelector.getSupportedIssuerBindings().addAll(getMessageEncoderFactory().getEncoderBuilders().keySet());
449 Endpoint relyingPartyEndpoint = endpointSelector.selectEndpoint();
451 MessageEncoder<ServletResponse> encoder = getMessageEncoderFactory().getMessageEncoder(
452 relyingPartyEndpoint.getBinding());
453 if (encoder == null) {
454 log.error("No response encoder was registered for binding type: " + relyingPartyEndpoint.getBinding());
455 throw new ProfileException("No response encoder was registered for binding type: "
456 + relyingPartyEndpoint.getBinding());
459 super.populateMessageEncoder(encoder);
460 encoder.setIssuer(requestContext.getAssertingPartyId());
461 encoder.setRelyingParty(requestContext.getRelyingPartyMetadata());
462 encoder.setRelyingPartyEndpoint(relyingPartyEndpoint);
463 encoder.setRelyingPartyRole(requestContext.getRelyingPartyRoleMetadata());
464 ProfileResponse<ServletResponse> profileResponse = requestContext.getProfileResponse();
465 encoder.setResponse(profileResponse.getRawResponse());
466 encoder.setSamlMessage(requestContext.getSamlResponse());
467 requestContext.setMessageEncoder(encoder);
471 } catch (BindingException e) {
472 throw new ProfileException("Unable to encode response to relying party: "
473 + requestContext.getRelyingPartyId(), e);
477 /** Represents the internal state of a SAML 2.0 SSO Request while it's being processed by the IdP. */
478 protected class SSORequestContext extends SAML2ProfileRequestContext<AuthnRequest, Response, SSOConfiguration> {
480 /** Current login context. */
481 private Saml2LoginContext loginContext;
486 * @param request current profile request
487 * @param response current profile response
489 public SSORequestContext(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response) {
490 super(request, response);
494 * Gets the current login context.
496 * @return current login context
498 public Saml2LoginContext getLoginContext() {
503 * Sets the current login context.
505 * @param context current login context
507 public void setLoginContext(Saml2LoginContext context) {
508 loginContext = context;