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.apache.log4j.Logger;
28 import org.opensaml.common.SAMLObjectBuilder;
29 import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
30 import org.opensaml.common.xml.SAMLConstants;
31 import org.opensaml.saml2.binding.AuthnResponseEndpointSelector;
32 import org.opensaml.saml2.core.AuthnContext;
33 import org.opensaml.saml2.core.AuthnContextClassRef;
34 import org.opensaml.saml2.core.AuthnContextDeclRef;
35 import org.opensaml.saml2.core.AuthnRequest;
36 import org.opensaml.saml2.core.AuthnStatement;
37 import org.opensaml.saml2.core.RequestedAuthnContext;
38 import org.opensaml.saml2.core.Response;
39 import org.opensaml.saml2.core.Statement;
40 import org.opensaml.saml2.core.StatusCode;
41 import org.opensaml.saml2.core.SubjectLocality;
42 import org.opensaml.saml2.metadata.AssertionConsumerService;
43 import org.opensaml.saml2.metadata.Endpoint;
44 import org.opensaml.saml2.metadata.EntityDescriptor;
45 import org.opensaml.saml2.metadata.IDPSSODescriptor;
46 import org.opensaml.saml2.metadata.SPSSODescriptor;
47 import org.opensaml.saml2.metadata.provider.MetadataProvider;
48 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
49 import org.opensaml.ws.message.decoder.MessageDecodingException;
50 import org.opensaml.ws.security.SecurityPolicyException;
51 import org.opensaml.ws.transport.http.HTTPInTransport;
52 import org.opensaml.ws.transport.http.HTTPOutTransport;
53 import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
54 import org.opensaml.ws.transport.http.HttpServletResponseAdapter;
55 import org.opensaml.xml.io.MarshallingException;
56 import org.opensaml.xml.io.UnmarshallingException;
58 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
59 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
60 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.SSOConfiguration;
61 import edu.internet2.middleware.shibboleth.common.util.HttpHelper;
62 import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
63 import edu.internet2.middleware.shibboleth.idp.authn.Saml2LoginContext;
65 /** SAML 2.0 SSO request profile handler. */
66 public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
69 private final Logger log = Logger.getLogger(SSOProfileHandler.class);
71 /** Builder of AuthnStatement objects. */
72 private SAMLObjectBuilder<AuthnStatement> authnStatementBuilder;
74 /** Builder of AuthnContext objects. */
75 private SAMLObjectBuilder<AuthnContext> authnContextBuilder;
77 /** Builder of AuthnContextClassRef objects. */
78 private SAMLObjectBuilder<AuthnContextClassRef> authnContextClassRefBuilder;
80 /** Builder of AuthnContextDeclRef objects. */
81 private SAMLObjectBuilder<AuthnContextDeclRef> authnContextDeclRefBuilder;
83 /** Builder of SubjectLocality objects. */
84 private SAMLObjectBuilder<SubjectLocality> subjectLocalityBuilder;
86 /** URL of the authentication manager servlet. */
87 private String authenticationManagerPath;
89 /** URI of request decoder. */
90 private String decodingBinding;
95 * @param authnManagerPath path to the authentication manager servlet
97 @SuppressWarnings("unchecked")
98 public SSOProfileHandler(String authnManagerPath) {
101 authenticationManagerPath = authnManagerPath;
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);
111 subjectLocalityBuilder = (SAMLObjectBuilder<SubjectLocality>) getBuilderFactory().getBuilder(
112 SubjectLocality.DEFAULT_ELEMENT_NAME);
116 public String getProfileId() {
117 return "urn:mace:shibboleth:2.0:idp:profiles:saml2:request:sso";
121 public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
122 HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
123 HttpSession httpSession = servletRequest.getSession();
125 if (httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY) == null) {
126 performAuthentication(inTransport, outTransport);
128 completeAuthenticationRequest(inTransport, outTransport);
133 * Creates a {@link Saml2LoginContext} an sends the request off to the AuthenticationManager to begin the process of
134 * authenticating the user.
136 * @param inTransport inbound request transport
137 * @param outTransport outbound response transport
139 * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
140 * authentication manager
142 protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
143 throws ProfileException {
144 HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
147 SSORequestContext requestContext = decodeRequest(inTransport, outTransport);
149 String relyingPartyId = requestContext.getPeerEntityId();
150 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
151 if (rpConfig == null) {
152 log.error("No relying party configuration for " + relyingPartyId);
153 throw new ProfileException("No relying party configuration for " + relyingPartyId);
156 Saml2LoginContext loginContext = new Saml2LoginContext(relyingPartyId, requestContext.getRelayState(),
157 requestContext.getInboundSAMLMessage());
158 loginContext.setAuthenticationEngineURL(authenticationManagerPath);
159 loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(servletRequest));
160 if (loginContext.getRequestedAuthenticationMethods().size() == 0) {
161 loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
164 HttpSession httpSession = servletRequest.getSession();
165 httpSession.setAttribute(Saml2LoginContext.LOGIN_CONTEXT_KEY, loginContext);
166 RequestDispatcher dispatcher = servletRequest.getRequestDispatcher(authenticationManagerPath);
167 dispatcher.forward(servletRequest, ((HttpServletResponseAdapter) outTransport).getWrappedResponse());
168 } catch (MarshallingException e) {
169 log.error("Unable to marshall authentication request context");
170 throw new ProfileException("Unable to marshall authentication request context", e);
171 } catch (IOException ex) {
172 log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
173 throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
174 } catch (ServletException ex) {
175 log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
176 throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
181 * Creates a response to the {@link AuthnRequest} and sends the user, with response in tow, back to the relying
182 * party after they've been authenticated.
184 * @param inTransport inbound message transport
185 * @param outTransport outbound message transport
187 * @throws ProfileException thrown if the response can not be created and sent back to the relying party
189 protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
190 throws ProfileException {
191 HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
192 HttpSession httpSession = servletRequest.getSession();
194 Saml2LoginContext loginContext = (Saml2LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
195 httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
197 SSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
199 checkSamlVersion(requestContext);
201 Response samlResponse;
203 if (loginContext.getPrincipalName() == null) {
204 log.error("User's login context did not contain a principal, user considered unauthenticiated.");
206 .setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI, null));
207 throw new ProfileException("User failed authentication");
210 resolveAttributes(requestContext);
212 ArrayList<Statement> statements = new ArrayList<Statement>();
213 statements.add(buildAuthnStatement(requestContext));
214 if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
215 requestContext.setRequestedAttributes(requestContext.getPrincipalAttributes().keySet());
216 statements.add(buildAttributeStatement(requestContext));
219 samlResponse = buildResponse(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:bearer", statements);
220 } catch (ProfileException e) {
221 samlResponse = buildErrorResponse(requestContext);
224 requestContext.setOutboundSAMLMessage(samlResponse);
225 requestContext.setOutboundSAMLMessageId(samlResponse.getID());
226 requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
227 encodeResponse(requestContext);
228 writeAuditLogEntry(requestContext);
232 * Decodes an incoming request and stores the information in a created request context.
234 * @param inTransport inbound transport
235 * @param outTransport outbound transport
237 * @return request context with decoded information
239 * @throws ProfileException thrown if the incomming message failed decoding
241 protected SSORequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
242 throws ProfileException {
243 if (log.isDebugEnabled()) {
244 log.debug("Decoding message with decoder binding " + decodingBinding);
247 SSORequestContext requestContext = new SSORequestContext();
248 requestContext.setMetadataProvider(getMetadataProvider());
250 requestContext.setInboundMessageTransport(inTransport);
251 requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
252 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
254 requestContext.setOutboundMessageTransport(outTransport);
255 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
258 SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
259 requestContext.setMessageDecoder(decoder);
260 decoder.decode(requestContext);
261 return requestContext;
262 } catch (MessageDecodingException e) {
263 log.error("Error decoding authentication request message", e);
264 throw new ProfileException("Error decoding authentication request message", e);
265 } catch (SecurityPolicyException e) {
266 log.error("Message did not meet security policy requirements", e);
267 throw new ProfileException("Message did not meet security policy requirements", e);
272 * Creates an authentication request context from the current environmental information.
274 * @param loginContext current login context
275 * @param in inbound transport
276 * @param out outbount transport
278 * @return created authentication request context
280 * @throws ProfileException thrown if there is a problem creating the context
282 protected SSORequestContext buildRequestContext(Saml2LoginContext loginContext, HTTPInTransport in,
283 HTTPOutTransport out) throws ProfileException {
284 SSORequestContext requestContext = new SSORequestContext();
287 requestContext.setLoginContext(loginContext);
288 requestContext.setPrincipalName(loginContext.getPrincipalName());
289 requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
290 requestContext.setUserSession(getUserSession(in));
291 requestContext.setRelayState(loginContext.getRelayState());
293 requestContext.setInboundMessageTransport(in);
294 requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
295 requestContext.setInboundMessage(loginContext.getAuthenticationRequest());
296 requestContext.setInboundSAMLMessage(loginContext.getAuthenticationRequest());
297 requestContext.setInboundSAMLMessageId(loginContext.getAuthenticationRequest().getID());
299 MetadataProvider metadataProvider = getMetadataProvider();
300 requestContext.setMetadataProvider(metadataProvider);
302 String relyingPartyId = loginContext.getRelyingPartyId();
303 requestContext.setPeerEntityId(relyingPartyId);
304 EntityDescriptor relyingPartyMetadata = metadataProvider.getEntityDescriptor(relyingPartyId);
305 requestContext.setPeerEntityMetadata(relyingPartyMetadata);
306 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
307 requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS));
308 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
309 requestContext.setRelyingPartyConfiguration(rpConfig);
310 requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
312 String assertingPartyId = rpConfig.getProviderId();
313 requestContext.setLocalEntityId(assertingPartyId);
314 EntityDescriptor assertingPartyMetadata = metadataProvider.getEntityDescriptor(assertingPartyId);
315 requestContext.setLocalEntityMetadata(assertingPartyMetadata);
316 requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
317 requestContext.setLocalEntityRoleMetadata(assertingPartyMetadata
318 .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
320 requestContext.setOutboundMessageTransport(out);
321 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
322 SSOConfiguration profileConfig = (SSOConfiguration) rpConfig
323 .getProfileConfiguration(SSOConfiguration.PROFILE_ID);
324 requestContext.setProfileConfiguration(profileConfig);
325 requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
326 if (profileConfig.getSigningCredential() != null) {
327 requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
328 } else if (rpConfig.getDefaultSigningCredential() != null) {
329 requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
332 return requestContext;
333 } catch (UnmarshallingException e) {
334 log.error("Unable to unmarshall authentication request context");
335 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
336 "Error recovering request state"));
337 throw new ProfileException("Error recovering request state", e);
338 } catch (MetadataProviderException e) {
339 log.error("Unable to locate metadata for asserting or relying party");
341 .setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error locating party metadata"));
342 throw new ProfileException("Error locating party metadata");
347 * Creates an authentication statement for the current request.
349 * @param requestContext current request context
351 * @return constructed authentication statement
353 protected AuthnStatement buildAuthnStatement(SSORequestContext requestContext) {
354 Saml2LoginContext loginContext = requestContext.getLoginContext();
356 AuthnContext authnContext = buildAuthnContext(requestContext);
358 AuthnStatement statement = authnStatementBuilder.buildObject();
359 statement.setAuthnContext(authnContext);
360 statement.setAuthnInstant(loginContext.getAuthenticationInstant());
363 statement.setSessionIndex(null);
365 if (loginContext.getAuthenticationDuration() > 0) {
366 statement.setSessionNotOnOrAfter(loginContext.getAuthenticationInstant().plus(
367 loginContext.getAuthenticationDuration()));
370 statement.setSubjectLocality(buildSubjectLocality(requestContext));
376 * Creates an {@link AuthnContext} for a succesful authentication request.
378 * @param requestContext current request
380 * @return the built authn context
382 protected AuthnContext buildAuthnContext(SSORequestContext requestContext) {
383 AuthnContext authnContext = authnContextBuilder.buildObject();
385 Saml2LoginContext loginContext = requestContext.getLoginContext();
386 AuthnRequest authnRequest = requestContext.getInboundSAMLMessage();
387 RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
388 if (requestedAuthnContext != null) {
389 if (requestedAuthnContext.getAuthnContextClassRefs() != null) {
390 for (AuthnContextClassRef classRef : requestedAuthnContext.getAuthnContextClassRefs()) {
391 if (classRef.getAuthnContextClassRef().equals(loginContext.getAuthenticationMethod())) {
392 AuthnContextClassRef ref = authnContextClassRefBuilder.buildObject();
393 ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
394 authnContext.setAuthnContextClassRef(ref);
397 } else if (requestedAuthnContext.getAuthnContextDeclRefs() != null) {
398 for (AuthnContextDeclRef declRef : requestedAuthnContext.getAuthnContextDeclRefs()) {
399 if (declRef.getAuthnContextDeclRef().equals(loginContext.getAuthenticationMethod())) {
400 AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
401 ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
402 authnContext.setAuthnContextDeclRef(ref);
407 AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
408 ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
409 authnContext.setAuthnContextDeclRef(ref);
416 * Constructs the subject locality for the authentication statement.
418 * @param requestContext curent request context
420 * @return subject locality for the authentication statement
422 protected SubjectLocality buildSubjectLocality(SSORequestContext requestContext) {
423 HTTPInTransport transport = (HTTPInTransport) requestContext.getInboundMessageTransport();
424 SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
425 subjectLocality.setAddress(transport.getPeerAddress());
426 subjectLocality.setDNSName(transport.getPeerDomainName());
428 return subjectLocality;
432 * Selects the appropriate endpoint for the relying party and stores it in the request context.
434 * @param requestContext current request context
436 * @return Endpoint selected from the information provided in the request context
438 protected Endpoint selectEndpoint(SSORequestContext requestContext) {
439 AuthnResponseEndpointSelector endpointSelector = new AuthnResponseEndpointSelector();
440 endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
441 endpointSelector.setMetadataProvider(getMetadataProvider());
442 endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
443 endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
444 endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
445 endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
446 return endpointSelector.selectEndpoint();
449 /** Represents the internal state of a SAML 2.0 SSO Request while it's being processed by the IdP. */
450 protected class SSORequestContext extends BaseSAML2ProfileRequestContext<AuthnRequest, Response, SSOConfiguration> {
452 /** Current login context. */
453 private Saml2LoginContext loginContext;
456 * Gets the current login context.
458 * @return current login context
460 public Saml2LoginContext getLoginContext() {
465 * Sets the current login context.
467 * @param context current login context
469 public void setLoginContext(Saml2LoginContext context) {
470 loginContext = context;