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.saml1;
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.HttpServletResponse;
27 import org.opensaml.common.SAMLObjectBuilder;
28 import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
29 import org.opensaml.common.xml.SAMLConstants;
30 import org.opensaml.saml1.core.AttributeStatement;
31 import org.opensaml.saml1.core.AuthenticationStatement;
32 import org.opensaml.saml1.core.Request;
33 import org.opensaml.saml1.core.Response;
34 import org.opensaml.saml1.core.Statement;
35 import org.opensaml.saml1.core.StatusCode;
36 import org.opensaml.saml1.core.Subject;
37 import org.opensaml.saml1.core.SubjectLocality;
38 import org.opensaml.saml2.metadata.AssertionConsumerService;
39 import org.opensaml.saml2.metadata.Endpoint;
40 import org.opensaml.saml2.metadata.EntityDescriptor;
41 import org.opensaml.saml2.metadata.IDPSSODescriptor;
42 import org.opensaml.saml2.metadata.SPSSODescriptor;
43 import org.opensaml.ws.message.decoder.MessageDecodingException;
44 import org.opensaml.ws.transport.http.HTTPInTransport;
45 import org.opensaml.ws.transport.http.HTTPOutTransport;
46 import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
47 import org.opensaml.ws.transport.http.HttpServletResponseAdapter;
48 import org.opensaml.xml.security.SecurityException;
49 import org.opensaml.xml.util.DatatypeHelper;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
53 import edu.internet2.middleware.shibboleth.common.ShibbolethConstants;
54 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
55 import edu.internet2.middleware.shibboleth.common.profile.provider.BaseSAMLProfileRequestContext;
56 import edu.internet2.middleware.shibboleth.common.relyingparty.ProfileConfiguration;
57 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
58 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml1.ShibbolethSSOConfiguration;
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.ShibbolethSSOLoginContext;
63 /** Shibboleth SSO request profile handler. */
64 public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
67 private final Logger log = LoggerFactory.getLogger(ShibbolethSSOProfileHandler.class);
69 /** Builder of AuthenticationStatement objects. */
70 private SAMLObjectBuilder<AuthenticationStatement> authnStatementBuilder;
72 /** Builder of SubjectLocality objects. */
73 private SAMLObjectBuilder<SubjectLocality> subjectLocalityBuilder;
75 /** Builder of Endpoint objects. */
76 private SAMLObjectBuilder<Endpoint> endpointBuilder;
78 /** URL of the authentication manager servlet. */
79 private String authenticationManagerPath;
84 * @param authnManagerPath path to the authentication manager servlet
86 * @throws IllegalArgumentException thrown if either the authentication manager path or encoding binding URI are
89 public ShibbolethSSOProfileHandler(String authnManagerPath) {
90 if (DatatypeHelper.isEmpty(authnManagerPath)) {
91 throw new IllegalArgumentException("Authentication manager path may not be null");
93 authenticationManagerPath = authnManagerPath;
95 authnStatementBuilder = (SAMLObjectBuilder<AuthenticationStatement>) getBuilderFactory().getBuilder(
96 AuthenticationStatement.DEFAULT_ELEMENT_NAME);
98 subjectLocalityBuilder = (SAMLObjectBuilder<SubjectLocality>) getBuilderFactory().getBuilder(
99 SubjectLocality.DEFAULT_ELEMENT_NAME);
101 endpointBuilder = (SAMLObjectBuilder<Endpoint>) getBuilderFactory().getBuilder(
102 AssertionConsumerService.DEFAULT_ELEMENT_NAME);
106 public String getProfileId() {
107 return ShibbolethSSOConfiguration.PROFILE_ID;
111 public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
112 log.debug("Processing incoming request");
114 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
115 LoginContext loginContext = (LoginContext) httpRequest.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
117 if (loginContext == null) {
118 log.debug("Incoming request does not contain a login context, processing as first leg of request");
119 performAuthentication(inTransport, outTransport);
121 log.debug("Incoming request contains a login context, processing as second leg of request");
122 completeAuthenticationRequest(inTransport, outTransport);
127 * Creates a {@link LoginContext} an sends the request off to the AuthenticationManager to begin the process of
128 * authenticating the user.
130 * @param inTransport inbound message transport
131 * @param outTransport outbound message transport
133 * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
134 * authentication manager
136 protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
137 throws ProfileException {
139 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
140 HttpServletResponse httpResponse = ((HttpServletResponseAdapter) outTransport).getWrappedResponse();
142 ShibbolethSSORequestContext requestContext = decodeRequest(inTransport, outTransport);
143 ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
145 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(loginContext.getRelyingPartyId());
146 ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID);
147 if (ssoConfig == null) {
148 log.error("Shibboleth SSO profile is not configured for relying party " + loginContext.getRelyingPartyId());
149 throw new ProfileException("Shibboleth SSO profile is not configured for relying party "
150 + loginContext.getRelyingPartyId());
152 loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
154 httpRequest.setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
157 RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
158 dispatcher.forward(httpRequest, httpResponse);
160 } catch (IOException ex) {
161 log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
162 throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
163 } catch (ServletException ex) {
164 log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
165 throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
170 * Decodes an incoming request and populates a created request context with the resultant information.
172 * @param inTransport inbound message transport
173 * @param outTransport outbound message transport
175 * @return the created request context
177 * @throws ProfileException throw if there is a problem decoding the request
179 protected ShibbolethSSORequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
180 throws ProfileException {
181 log.debug("Decoding message with decoder binding {}", getInboundBinding());
183 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
185 ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
186 requestContext.setMetadataProvider(getMetadataProvider());
187 requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
189 requestContext.setCommunicationProfileId(ShibbolethSSOConfiguration.PROFILE_ID);
190 requestContext.setInboundMessageTransport(inTransport);
191 requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
192 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
194 requestContext.setOutboundMessageTransport(outTransport);
195 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML11P_NS);
197 SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
198 requestContext.setMessageDecoder(decoder);
200 decoder.decode(requestContext);
201 } catch (MessageDecodingException e) {
202 log.error("Error decoding Shibboleth SSO request", e);
203 throw new ProfileException("Error decoding Shibboleth SSO request", e);
204 } catch (SecurityException e) {
205 log.error("Shibboleth SSO request does not meet security requirements", e);
206 throw new ProfileException("Shibboleth SSO request does not meet security requirements", e);
209 ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
210 loginContext.setRelyingParty(requestContext.getInboundMessageIssuer());
211 loginContext.setSpAssertionConsumerService(requestContext.getSpAssertionConsumerService());
212 loginContext.setSpTarget(requestContext.getRelayState());
213 loginContext.setAuthenticationEngineURL(authenticationManagerPath);
214 loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
215 requestContext.setLoginContext(loginContext);
217 return requestContext;
221 * Creates a response to the Shibboleth SSO and sends the user, with response in tow, back to the relying party
222 * after they've been authenticated.
224 * @param inTransport inbound message transport
225 * @param outTransport outbound message transport
227 * @throws ProfileException thrown if the response can not be created and sent back to the relying party
229 protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
230 throws ProfileException {
231 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
232 ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) httpRequest
233 .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
235 ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
237 Response samlResponse;
239 if (loginContext.getAuthenticationFailure() != null) {
240 log.error("User authentication failed with the following error: {}", loginContext
241 .getAuthenticationFailure().toString());
242 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "User failed authentication"));
243 throw new ProfileException("Authentication failure", loginContext.getAuthenticationFailure());
246 resolveAttributes(requestContext);
248 ArrayList<Statement> statements = new ArrayList<Statement>();
249 statements.add(buildAuthenticationStatement(requestContext));
250 if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
251 AttributeStatement attributeStatement = buildAttributeStatement(requestContext,
252 "urn:oasis:names:tc:SAML:1.0:cm:bearer");
253 if (attributeStatement != null) {
254 requestContext.setRequestedAttributes(requestContext.getAttributes().keySet());
255 statements.add(attributeStatement);
259 samlResponse = buildResponse(requestContext, statements);
260 } catch (ProfileException e) {
261 samlResponse = buildErrorResponse(requestContext);
264 requestContext.setOutboundSAMLMessage(samlResponse);
265 requestContext.setOutboundSAMLMessageId(samlResponse.getID());
266 requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
267 encodeResponse(requestContext);
268 writeAuditLogEntry(requestContext);
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 ShibbolethSSORequestContext buildRequestContext(ShibbolethSSOLoginContext loginContext,
283 HTTPInTransport in, HTTPOutTransport out) throws ProfileException {
284 ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
286 requestContext.setMessageDecoder(getMessageDecoders().get(getInboundBinding()));
288 requestContext.setLoginContext(loginContext);
289 requestContext.setRelayState(loginContext.getSpTarget());
291 requestContext.setInboundMessageTransport(in);
292 requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
294 requestContext.setOutboundMessageTransport(out);
295 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
297 requestContext.setMetadataProvider(getMetadataProvider());
299 String relyingPartyId = loginContext.getRelyingPartyId();
300 requestContext.setPeerEntityId(relyingPartyId);
301 requestContext.setInboundMessageIssuer(relyingPartyId);
303 populateRequestContext(requestContext);
305 return requestContext;
309 protected void populateRelyingPartyInformation(BaseSAMLProfileRequestContext requestContext)
310 throws ProfileException {
311 super.populateRelyingPartyInformation(requestContext);
313 EntityDescriptor relyingPartyMetadata = requestContext.getPeerEntityMetadata();
314 if (relyingPartyMetadata != null) {
315 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
316 requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML11P_NS));
321 protected void populateAssertingPartyInformation(BaseSAMLProfileRequestContext requestContext)
322 throws ProfileException {
323 super.populateAssertingPartyInformation(requestContext);
325 EntityDescriptor localEntityDescriptor = requestContext.getLocalEntityMetadata();
326 if (localEntityDescriptor != null) {
327 requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
328 requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
329 .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
334 protected void populateSAMLMessageInformation(BaseSAMLProfileRequestContext requestContext) throws ProfileException {
335 // nothing to do here
339 * Selects the appropriate endpoint for the relying party and stores it in the request context.
341 * @param requestContext current request context
343 * @return Endpoint selected from the information provided in the request context
345 protected Endpoint selectEndpoint(BaseSAMLProfileRequestContext requestContext) {
346 ShibbolethSSOLoginContext loginContext = ((ShibbolethSSORequestContext) requestContext).getLoginContext();
348 ShibbolethSSOEndpointSelector endpointSelector = new ShibbolethSSOEndpointSelector();
349 endpointSelector.setSpAssertionConsumerService(loginContext.getSpAssertionConsumerService());
350 endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
351 endpointSelector.setMetadataProvider(getMetadataProvider());
352 endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
353 endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
354 endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
355 endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
357 Endpoint endpoint = endpointSelector.selectEndpoint();
358 if (endpoint == null && loginContext.getSpAssertionConsumerService() != null) {
359 endpoint = endpointBuilder.buildObject();
360 endpoint.setLocation(loginContext.getSpAssertionConsumerService());
361 endpoint.setBinding(getInboundBinding());
362 log.warn("No endpoint available for relying party {}. Generating endpoint with ACS url {} and binding {}",
363 new Object[] { requestContext.getPeerEntityId(), endpoint.getLocation(), endpoint.getBinding() });
370 * Builds the authentication statement for the authenticated principal.
372 * @param requestContext current request context
374 * @return the created statement
376 * @throws ProfileException thrown if the authentication statement can not be created
378 protected AuthenticationStatement buildAuthenticationStatement(ShibbolethSSORequestContext requestContext)
379 throws ProfileException {
380 ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
382 AuthenticationStatement statement = authnStatementBuilder.buildObject();
383 statement.setAuthenticationInstant(loginContext.getAuthenticationInstant());
384 statement.setAuthenticationMethod(loginContext.getAuthenticationMethod());
386 statement.setSubjectLocality(buildSubjectLocality(requestContext));
388 Subject statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:bearer");
389 statement.setSubject(statementSubject);
395 * Constructs the subject locality for the authentication statement.
397 * @param requestContext curent request context
399 * @return subject locality for the authentication statement
401 protected SubjectLocality buildSubjectLocality(ShibbolethSSORequestContext requestContext) {
402 SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
404 HTTPInTransport inTransport = (HTTPInTransport) requestContext.getInboundMessageTransport();
405 subjectLocality.setIPAddress(inTransport.getPeerAddress());
407 return subjectLocality;
410 /** Represents the internal state of a Shibboleth SSO Request while it's being processed by the IdP. */
411 public class ShibbolethSSORequestContext extends
412 BaseSAML1ProfileRequestContext<Request, Response, ShibbolethSSOConfiguration> {
414 /** SP-provide assertion consumer service URL. */
415 private String spAssertionConsumerService;
417 /** Current login context. */
418 private ShibbolethSSOLoginContext loginContext;
421 * Gets the current login context.
423 * @return current login context
425 public ShibbolethSSOLoginContext getLoginContext() {
430 * Sets the current login context.
432 * @param context current login context
434 public void setLoginContext(ShibbolethSSOLoginContext context) {
435 loginContext = context;
439 * Gets the SP-provided assertion consumer service URL.
441 * @return SP-provided assertion consumer service URL
443 public String getSpAssertionConsumerService() {
444 return spAssertionConsumerService;
448 * Sets the SP-provided assertion consumer service URL.
450 * @param acs SP-provided assertion consumer service URL
452 public void setSpAssertionConsumerService(String acs) {
453 spAssertionConsumerService = acs;