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.setInboundMessageTransport(inTransport);
249 requestContext.setOutboundMessageTransport(outTransport);
250 requestContext.setMetadataProvider(getMetadataProvider());
253 SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
254 requestContext.setMessageDecoder(decoder);
255 decoder.decode(requestContext);
256 return requestContext;
257 } catch (MessageDecodingException e) {
258 log.error("Error decoding authentication request message", e);
259 throw new ProfileException("Error decoding authentication request message", e);
260 } catch (SecurityPolicyException e) {
261 log.error("Message did not meet security policy requirements", e);
262 throw new ProfileException("Message did not meet security policy requirements", e);
267 * Creates an authentication request context from the current environmental information.
269 * @param loginContext current login context
270 * @param in inbound transport
271 * @param out outbount transport
273 * @return created authentication request context
275 * @throws ProfileException thrown if there is a problem creating the context
277 protected SSORequestContext buildRequestContext(Saml2LoginContext loginContext, HTTPInTransport in,
278 HTTPOutTransport out) throws ProfileException {
279 SSORequestContext requestContext = new SSORequestContext();
282 requestContext.setLoginContext(loginContext);
283 requestContext.setPrincipalName(loginContext.getPrincipalName());
284 requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
285 requestContext.setUserSession(getUserSession(in));
286 requestContext.setRelayState(loginContext.getRelayState());
288 requestContext.setInboundMessageTransport(in);
289 requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
290 requestContext.setInboundMessage(loginContext.getAuthenticationRequest());
291 requestContext.setInboundSAMLMessage(loginContext.getAuthenticationRequest());
292 requestContext.setInboundSAMLMessageId(loginContext.getAuthenticationRequest().getID());
294 MetadataProvider metadataProvider = getMetadataProvider();
295 requestContext.setMetadataProvider(metadataProvider);
297 String relyingPartyId = loginContext.getRelyingPartyId();
298 requestContext.setPeerEntityId(relyingPartyId);
299 EntityDescriptor relyingPartyMetadata = metadataProvider.getEntityDescriptor(relyingPartyId);
300 requestContext.setPeerEntityMetadata(relyingPartyMetadata);
301 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
302 requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS));
303 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
304 requestContext.setRelyingPartyConfiguration(rpConfig);
305 requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
307 String assertingPartyId = rpConfig.getProviderId();
308 requestContext.setLocalEntityId(assertingPartyId);
309 EntityDescriptor assertingPartyMetadata = metadataProvider.getEntityDescriptor(assertingPartyId);
310 requestContext.setLocalEntityMetadata(assertingPartyMetadata);
311 requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
312 requestContext.setLocalEntityRoleMetadata(assertingPartyMetadata
313 .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
315 requestContext.setOutboundMessageTransport(out);
316 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
317 SSOConfiguration profileConfig = (SSOConfiguration) rpConfig
318 .getProfileConfiguration(SSOConfiguration.PROFILE_ID);
319 requestContext.setProfileConfiguration(profileConfig);
320 requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
321 if (profileConfig.getSigningCredential() != null) {
322 requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
323 } else if (rpConfig.getDefaultSigningCredential() != null) {
324 requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
327 return requestContext;
328 } catch (UnmarshallingException e) {
329 log.error("Unable to unmarshall authentication request context");
330 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
331 "Error recovering request state"));
332 throw new ProfileException("Error recovering request state", e);
333 } catch (MetadataProviderException e) {
334 log.error("Unable to locate metadata for asserting or relying party");
336 .setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error locating party metadata"));
337 throw new ProfileException("Error locating party metadata");
342 * Creates an authentication statement for the current request.
344 * @param requestContext current request context
346 * @return constructed authentication statement
348 protected AuthnStatement buildAuthnStatement(SSORequestContext requestContext) {
349 Saml2LoginContext loginContext = requestContext.getLoginContext();
351 AuthnContext authnContext = buildAuthnContext(requestContext);
353 AuthnStatement statement = authnStatementBuilder.buildObject();
354 statement.setAuthnContext(authnContext);
355 statement.setAuthnInstant(loginContext.getAuthenticationInstant());
358 statement.setSessionIndex(null);
360 if (loginContext.getAuthenticationDuration() > 0) {
361 statement.setSessionNotOnOrAfter(loginContext.getAuthenticationInstant().plus(
362 loginContext.getAuthenticationDuration()));
365 statement.setSubjectLocality(buildSubjectLocality(requestContext));
371 * Creates an {@link AuthnContext} for a succesful authentication request.
373 * @param requestContext current request
375 * @return the built authn context
377 protected AuthnContext buildAuthnContext(SSORequestContext requestContext) {
378 AuthnContext authnContext = authnContextBuilder.buildObject();
380 Saml2LoginContext loginContext = requestContext.getLoginContext();
381 AuthnRequest authnRequest = requestContext.getInboundSAMLMessage();
382 RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
383 if (requestedAuthnContext != null) {
384 if (requestedAuthnContext.getAuthnContextClassRefs() != null) {
385 for (AuthnContextClassRef classRef : requestedAuthnContext.getAuthnContextClassRefs()) {
386 if (classRef.getAuthnContextClassRef().equals(loginContext.getAuthenticationMethod())) {
387 AuthnContextClassRef ref = authnContextClassRefBuilder.buildObject();
388 ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
389 authnContext.setAuthnContextClassRef(ref);
392 } else if (requestedAuthnContext.getAuthnContextDeclRefs() != null) {
393 for (AuthnContextDeclRef declRef : requestedAuthnContext.getAuthnContextDeclRefs()) {
394 if (declRef.getAuthnContextDeclRef().equals(loginContext.getAuthenticationMethod())) {
395 AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
396 ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
397 authnContext.setAuthnContextDeclRef(ref);
402 AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
403 ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
404 authnContext.setAuthnContextDeclRef(ref);
411 * Constructs the subject locality for the authentication statement.
413 * @param requestContext curent request context
415 * @return subject locality for the authentication statement
417 protected SubjectLocality buildSubjectLocality(SSORequestContext requestContext) {
418 HTTPInTransport transport = (HTTPInTransport) requestContext.getInboundMessageTransport();
419 SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
420 subjectLocality.setAddress(transport.getPeerAddress());
421 subjectLocality.setDNSName(transport.getPeerDomainName());
423 return subjectLocality;
427 * Selects the appropriate endpoint for the relying party and stores it in the request context.
429 * @param requestContext current request context
431 * @return Endpoint selected from the information provided in the request context
433 protected Endpoint selectEndpoint(SSORequestContext requestContext) {
434 AuthnResponseEndpointSelector endpointSelector = new AuthnResponseEndpointSelector();
435 endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
436 endpointSelector.setMetadataProvider(getMetadataProvider());
437 endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
438 endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
439 endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
440 endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
441 return endpointSelector.selectEndpoint();
444 /** Represents the internal state of a SAML 2.0 SSO Request while it's being processed by the IdP. */
445 protected class SSORequestContext extends BaseSAML2ProfileRequestContext<AuthnRequest, Response, SSOConfiguration> {
447 /** Current login context. */
448 private Saml2LoginContext loginContext;
451 * Gets the current login context.
453 * @return current login context
455 public Saml2LoginContext getLoginContext() {
460 * Sets the current login context.
462 * @param context current login context
464 public void setLoginContext(Saml2LoginContext context) {
465 loginContext = context;