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;
21 import java.util.List;
23 import javax.servlet.RequestDispatcher;
24 import javax.servlet.ServletException;
25 import javax.servlet.http.HttpServletRequest;
26 import javax.servlet.http.HttpSession;
28 import org.apache.log4j.Logger;
29 import org.opensaml.common.SAMLObjectBuilder;
30 import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
31 import org.opensaml.common.xml.SAMLConstants;
32 import org.opensaml.saml2.binding.AuthnResponseEndpointSelector;
33 import org.opensaml.saml2.core.AuthnContext;
34 import org.opensaml.saml2.core.AuthnContextClassRef;
35 import org.opensaml.saml2.core.AuthnContextDeclRef;
36 import org.opensaml.saml2.core.AuthnRequest;
37 import org.opensaml.saml2.core.AuthnStatement;
38 import org.opensaml.saml2.core.RequestedAuthnContext;
39 import org.opensaml.saml2.core.Response;
40 import org.opensaml.saml2.core.Statement;
41 import org.opensaml.saml2.core.StatusCode;
42 import org.opensaml.saml2.core.SubjectLocality;
43 import org.opensaml.saml2.metadata.AssertionConsumerService;
44 import org.opensaml.saml2.metadata.Endpoint;
45 import org.opensaml.saml2.metadata.EntityDescriptor;
46 import org.opensaml.saml2.metadata.IDPSSODescriptor;
47 import org.opensaml.saml2.metadata.SPSSODescriptor;
48 import org.opensaml.saml2.metadata.provider.MetadataProvider;
49 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
50 import org.opensaml.ws.message.decoder.MessageDecodingException;
51 import org.opensaml.ws.security.SecurityPolicyException;
52 import org.opensaml.ws.transport.http.HTTPInTransport;
53 import org.opensaml.ws.transport.http.HTTPOutTransport;
54 import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
55 import org.opensaml.ws.transport.http.HttpServletResponseAdapter;
56 import org.opensaml.xml.io.MarshallingException;
57 import org.opensaml.xml.io.UnmarshallingException;
59 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
60 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
61 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.SSOConfiguration;
62 import edu.internet2.middleware.shibboleth.common.util.HttpHelper;
63 import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
64 import edu.internet2.middleware.shibboleth.idp.authn.Saml2LoginContext;
66 /** SAML 2.0 SSO request profile handler. */
67 public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
70 private final Logger log = Logger.getLogger(SSOProfileHandler.class);
72 /** Builder of AuthnStatement objects. */
73 private SAMLObjectBuilder<AuthnStatement> authnStatementBuilder;
75 /** Builder of AuthnContext objects. */
76 private SAMLObjectBuilder<AuthnContext> authnContextBuilder;
78 /** Builder of AuthnContextClassRef objects. */
79 private SAMLObjectBuilder<AuthnContextClassRef> authnContextClassRefBuilder;
81 /** Builder of AuthnContextDeclRef objects. */
82 private SAMLObjectBuilder<AuthnContextDeclRef> authnContextDeclRefBuilder;
84 /** Builder of SubjectLocality objects. */
85 private SAMLObjectBuilder<SubjectLocality> subjectLocalityBuilder;
87 /** URL of the authentication manager servlet. */
88 private String authenticationManagerPath;
90 /** URI of SAML 2 bindings supported for outgoing messaged encoding. */
91 private ArrayList<String> supportedOutgoingBindings;
93 /** URI of request decoder. */
94 private String decodingBinding;
99 * @param authnManagerPath path to the authentication manager servlet
100 * @param outgoingBindings URIs of SAML 2 bindings supported for outgoing message encoding
101 * @param decoder URI of the request decoder to use
103 @SuppressWarnings("unchecked")
104 public SSOProfileHandler(String authnManagerPath, List<String> outgoingBindings, String decoder) {
107 if (authnManagerPath == null || decoder == null) {
108 throw new IllegalArgumentException("AuthN manager path or decoding bindings URI may not be null");
110 authenticationManagerPath = authnManagerPath;
112 if (outgoingBindings == null || outgoingBindings.isEmpty()) {
113 throw new IllegalArgumentException("List of supported outgoing bindings may not be empty");
115 supportedOutgoingBindings = new ArrayList<String>(outgoingBindings);
117 decodingBinding = decoder;
119 authnStatementBuilder = (SAMLObjectBuilder<AuthnStatement>) getBuilderFactory().getBuilder(
120 AuthnStatement.DEFAULT_ELEMENT_NAME);
121 authnContextBuilder = (SAMLObjectBuilder<AuthnContext>) getBuilderFactory().getBuilder(
122 AuthnContext.DEFAULT_ELEMENT_NAME);
123 authnContextClassRefBuilder = (SAMLObjectBuilder<AuthnContextClassRef>) getBuilderFactory().getBuilder(
124 AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
125 authnContextDeclRefBuilder = (SAMLObjectBuilder<AuthnContextDeclRef>) getBuilderFactory().getBuilder(
126 AuthnContextDeclRef.DEFAULT_ELEMENT_NAME);
127 subjectLocalityBuilder = (SAMLObjectBuilder<SubjectLocality>) getBuilderFactory().getBuilder(
128 SubjectLocality.DEFAULT_ELEMENT_NAME);
132 public String getProfileId() {
133 return "urn:mace:shibboleth:2.0:idp:profiles:saml2:request:sso";
137 public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
138 HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
139 HttpSession httpSession = servletRequest.getSession();
141 if (httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY) == null) {
142 performAuthentication(inTransport, outTransport);
144 completeAuthenticationRequest(inTransport, outTransport);
149 * Creates a {@link Saml2LoginContext} an sends the request off to the AuthenticationManager to begin the process of
150 * authenticating the user.
152 * @param inTransport inbound request transport
153 * @param outTransport outbound response transport
155 * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
156 * authentication manager
158 protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
159 throws ProfileException {
160 HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
163 SSORequestContext requestContext = decodeRequest(inTransport, outTransport);
165 String relyingPartyId = requestContext.getPeerEntityId();
166 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
167 if (rpConfig == null) {
168 log.error("No relying party configuration for " + relyingPartyId);
169 throw new ProfileException("No relying party configuration for " + relyingPartyId);
172 Saml2LoginContext loginContext = new Saml2LoginContext(relyingPartyId, requestContext.getRelayState(),
173 requestContext.getInboundSAMLMessage());
174 loginContext.setAuthenticationEngineURL(authenticationManagerPath);
175 loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(servletRequest));
176 if (loginContext.getRequestedAuthenticationMethods().size() == 0) {
177 loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
180 HttpSession httpSession = servletRequest.getSession();
181 httpSession.setAttribute(Saml2LoginContext.LOGIN_CONTEXT_KEY, loginContext);
182 RequestDispatcher dispatcher = servletRequest.getRequestDispatcher(authenticationManagerPath);
183 dispatcher.forward(servletRequest, ((HttpServletResponseAdapter) outTransport).getWrappedResponse());
184 } catch (MarshallingException e) {
185 log.error("Unable to marshall authentication request context");
186 throw new ProfileException("Unable to marshall authentication request context", e);
187 } catch (IOException ex) {
188 log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
189 throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
190 } catch (ServletException ex) {
191 log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
192 throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
197 * Creates a response to the {@link AuthnRequest} and sends the user, with response in tow, back to the relying
198 * party after they've been authenticated.
200 * @param inTransport inbound message transport
201 * @param outTransport outbound message transport
203 * @throws ProfileException thrown if the response can not be created and sent back to the relying party
205 protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
206 throws ProfileException {
207 HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
208 HttpSession httpSession = servletRequest.getSession();
210 Saml2LoginContext loginContext = (Saml2LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
211 httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
213 SSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
215 checkSamlVersion(requestContext);
217 Response samlResponse;
219 if (loginContext.getPrincipalName() == null) {
220 log.error("User's login context did not contain a principal, user considered unauthenticiated.");
222 .setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI, null));
223 throw new ProfileException("User failed authentication");
226 resolveAttributes(requestContext);
228 ArrayList<Statement> statements = new ArrayList<Statement>();
229 statements.add(buildAuthnStatement(requestContext));
230 if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
231 requestContext.setRequestedAttributes(requestContext.getPrincipalAttributes().keySet());
232 statements.add(buildAttributeStatement(requestContext));
235 samlResponse = buildResponse(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:bearer", statements);
236 } catch (ProfileException e) {
237 samlResponse = buildErrorResponse(requestContext);
240 requestContext.setOutboundSAMLMessage(samlResponse);
241 requestContext.setOutboundSAMLMessageId(samlResponse.getID());
242 requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
243 encodeResponse(requestContext);
244 writeAuditLogEntry(requestContext);
248 * Decodes an incoming request and stores the information in a created request context.
250 * @param inTransport inbound transport
251 * @param outTransport outbound transport
253 * @return request context with decoded information
255 * @throws ProfileException thrown if the incomming message failed decoding
257 protected SSORequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
258 throws ProfileException {
259 if (log.isDebugEnabled()) {
260 log.debug("Decoding message with decoder binding " + decodingBinding);
263 SSORequestContext requestContext = new SSORequestContext();
264 requestContext.setInboundMessageTransport(inTransport);
265 requestContext.setOutboundMessageTransport(outTransport);
266 requestContext.setMetadataProvider(getMetadataProvider());
269 SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
270 requestContext.setMessageDecoder(decoder);
271 decoder.decode(requestContext);
272 return requestContext;
273 } catch (MessageDecodingException e) {
274 log.error("Error decoding authentication request message", e);
275 throw new ProfileException("Error decoding authentication request message", e);
276 } catch (SecurityPolicyException e) {
277 log.error("Message did not meet security policy requirements", e);
278 throw new ProfileException("Message did not meet security policy requirements", e);
283 * Creates an authentication request context from the current environmental information.
285 * @param loginContext current login context
286 * @param in inbound transport
287 * @param out outbount transport
289 * @return created authentication request context
291 * @throws ProfileException thrown if there is a problem creating the context
293 protected SSORequestContext buildRequestContext(Saml2LoginContext loginContext, HTTPInTransport in,
294 HTTPOutTransport out) throws ProfileException {
295 SSORequestContext requestContext = new SSORequestContext();
298 requestContext.setLoginContext(loginContext);
299 requestContext.setPrincipalName(loginContext.getPrincipalName());
300 requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
301 requestContext.setUserSession(getUserSession(in));
302 requestContext.setRelayState(loginContext.getRelayState());
304 requestContext.setInboundMessageTransport(in);
305 requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
306 requestContext.setInboundMessage(loginContext.getAuthenticationRequest());
307 requestContext.setInboundSAMLMessage(loginContext.getAuthenticationRequest());
308 requestContext.setInboundSAMLMessageId(loginContext.getAuthenticationRequest().getID());
310 MetadataProvider metadataProvider = getMetadataProvider();
311 requestContext.setMetadataProvider(metadataProvider);
313 String relyingPartyId = loginContext.getRelyingPartyId();
314 requestContext.setPeerEntityId(relyingPartyId);
315 EntityDescriptor relyingPartyMetadata = metadataProvider.getEntityDescriptor(relyingPartyId);
316 requestContext.setPeerEntityMetadata(relyingPartyMetadata);
317 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
318 requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS));
319 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
320 requestContext.setRelyingPartyConfiguration(rpConfig);
321 requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
323 String assertingPartyId = rpConfig.getProviderId();
324 requestContext.setLocalEntityId(assertingPartyId);
325 EntityDescriptor assertingPartyMetadata = metadataProvider.getEntityDescriptor(assertingPartyId);
326 requestContext.setLocalEntityMetadata(assertingPartyMetadata);
327 requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
328 requestContext.setLocalEntityRoleMetadata(assertingPartyMetadata
329 .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
331 requestContext.setOutboundMessageTransport(out);
332 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
333 SSOConfiguration profileConfig = (SSOConfiguration) rpConfig
334 .getProfileConfiguration(SSOConfiguration.PROFILE_ID);
335 requestContext.setProfileConfiguration(profileConfig);
336 if (profileConfig.getSigningCredential() != null) {
337 requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
338 } else if (rpConfig.getDefaultSigningCredential() != null) {
339 requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
342 return requestContext;
343 } catch (UnmarshallingException e) {
344 log.error("Unable to unmarshall authentication request context");
345 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
346 "Error recovering request state"));
347 throw new ProfileException("Error recovering request state", e);
348 } catch (MetadataProviderException e) {
349 log.error("Unable to locate metadata for asserting or relying party");
351 .setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error locating party metadata"));
352 throw new ProfileException("Error locating party metadata");
357 * Creates an authentication statement for the current request.
359 * @param requestContext current request context
361 * @return constructed authentication statement
363 protected AuthnStatement buildAuthnStatement(SSORequestContext requestContext) {
364 Saml2LoginContext loginContext = requestContext.getLoginContext();
366 AuthnContext authnContext = buildAuthnContext(requestContext);
368 AuthnStatement statement = authnStatementBuilder.buildObject();
369 statement.setAuthnContext(authnContext);
370 statement.setAuthnInstant(loginContext.getAuthenticationInstant());
373 statement.setSessionIndex(null);
375 if (loginContext.getAuthenticationDuration() > 0) {
376 statement.setSessionNotOnOrAfter(loginContext.getAuthenticationInstant().plus(
377 loginContext.getAuthenticationDuration()));
380 statement.setSubjectLocality(buildSubjectLocality(requestContext));
386 * Creates an {@link AuthnContext} for a succesful authentication request.
388 * @param requestContext current request
390 * @return the built authn context
392 protected AuthnContext buildAuthnContext(SSORequestContext requestContext) {
393 AuthnContext authnContext = authnContextBuilder.buildObject();
395 Saml2LoginContext loginContext = requestContext.getLoginContext();
396 AuthnRequest authnRequest = requestContext.getInboundSAMLMessage();
397 RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
398 if (requestedAuthnContext != null) {
399 if (requestedAuthnContext.getAuthnContextClassRefs() != null) {
400 for (AuthnContextClassRef classRef : requestedAuthnContext.getAuthnContextClassRefs()) {
401 if (classRef.getAuthnContextClassRef().equals(loginContext.getAuthenticationMethod())) {
402 AuthnContextClassRef ref = authnContextClassRefBuilder.buildObject();
403 ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
404 authnContext.setAuthnContextClassRef(ref);
407 } else if (requestedAuthnContext.getAuthnContextDeclRefs() != null) {
408 for (AuthnContextDeclRef declRef : requestedAuthnContext.getAuthnContextDeclRefs()) {
409 if (declRef.getAuthnContextDeclRef().equals(loginContext.getAuthenticationMethod())) {
410 AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
411 ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
412 authnContext.setAuthnContextDeclRef(ref);
417 AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
418 ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
419 authnContext.setAuthnContextDeclRef(ref);
426 * Constructs the subject locality for the authentication statement.
428 * @param requestContext curent request context
430 * @return subject locality for the authentication statement
432 protected SubjectLocality buildSubjectLocality(SSORequestContext requestContext) {
433 HTTPInTransport transport = (HTTPInTransport) requestContext.getInboundMessageTransport();
434 SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
435 subjectLocality.setAddress(transport.getPeerAddress());
436 subjectLocality.setDNSName(transport.getPeerDomainName());
438 return subjectLocality;
442 * Selects the appropriate endpoint for the relying party and stores it in the request context.
444 * @param requestContext current request context
446 * @return Endpoint selected from the information provided in the request context
448 protected Endpoint selectEndpoint(SSORequestContext requestContext) {
449 AuthnResponseEndpointSelector endpointSelector = new AuthnResponseEndpointSelector();
450 endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
451 endpointSelector.setMetadataProvider(getMetadataProvider());
452 endpointSelector.setRelyingParty(requestContext.getPeerEntityMetadata());
453 endpointSelector.setRelyingPartyRole(requestContext.getPeerEntityRoleMetadata());
454 endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
455 endpointSelector.getSupportedIssuerBindings().addAll(supportedOutgoingBindings);
456 return endpointSelector.selectEndpoint();
459 /** Represents the internal state of a SAML 2.0 SSO Request while it's being processed by the IdP. */
460 protected class SSORequestContext extends BaseSAML2ProfileRequestContext<AuthnRequest, Response, SSOConfiguration> {
462 /** Current login context. */
463 private Saml2LoginContext loginContext;
466 * Gets the current login context.
468 * @return current login context
470 public Saml2LoginContext getLoginContext() {
475 * Sets the current login context.
477 * @param context current login context
479 public void setLoginContext(Saml2LoginContext context) {
480 loginContext = context;