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(Endpoint.DEFAULT_ELEMENT_NAME);
105 public String getProfileId() {
106 return ShibbolethSSOConfiguration.PROFILE_ID;
110 public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
111 log.debug("Processing incoming request");
113 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
114 LoginContext loginContext = (LoginContext) httpRequest.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
116 if (loginContext == null) {
117 log.debug("Incoming request does not contain a login context, processing as first leg of request");
118 performAuthentication(inTransport, outTransport);
120 log.debug("Incoming request contains a login context, processing as second leg of request");
121 completeAuthenticationRequest(inTransport, outTransport);
126 * Creates a {@link LoginContext} an sends the request off to the AuthenticationManager to begin the process of
127 * authenticating the user.
129 * @param inTransport inbound message transport
130 * @param outTransport outbound message transport
132 * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
133 * authentication manager
135 protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
136 throws ProfileException {
138 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
139 HttpServletResponse httpResponse = ((HttpServletResponseAdapter) outTransport).getWrappedResponse();
141 ShibbolethSSORequestContext requestContext = decodeRequest(inTransport, outTransport);
142 ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
144 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(loginContext.getRelyingPartyId());
145 ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID);
146 if (ssoConfig == null) {
147 log.error("Shibboleth SSO profile is not configured for relying party " + loginContext.getRelyingPartyId());
148 throw new ProfileException("Shibboleth SSO profile is not configured for relying party "
149 + loginContext.getRelyingPartyId());
151 loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
153 httpRequest.setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
156 RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
157 dispatcher.forward(httpRequest, httpResponse);
159 } catch (IOException ex) {
160 log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
161 throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
162 } catch (ServletException ex) {
163 log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
164 throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
169 * Decodes an incoming request and populates a created request context with the resultant information.
171 * @param inTransport inbound message transport
172 * @param outTransport outbound message transport
174 * @return the created request context
176 * @throws ProfileException throw if there is a problem decoding the request
178 protected ShibbolethSSORequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
179 throws ProfileException {
180 log.debug("Decoding message with decoder binding {}", getInboundBinding());
182 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
184 ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
185 requestContext.setMetadataProvider(getMetadataProvider());
186 requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
188 requestContext.setCommunicationProfileId(ShibbolethSSOConfiguration.PROFILE_ID);
189 requestContext.setInboundMessageTransport(inTransport);
190 requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
191 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
193 requestContext.setOutboundMessageTransport(outTransport);
194 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML11P_NS);
196 SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
197 requestContext.setMessageDecoder(decoder);
199 decoder.decode(requestContext);
200 } catch (MessageDecodingException e) {
201 log.error("Error decoding Shibboleth SSO request", e);
202 throw new ProfileException("Error decoding Shibboleth SSO request", e);
203 } catch (SecurityException e) {
204 log.error("Shibboleth SSO request does not meet security requirements", e);
205 throw new ProfileException("Shibboleth SSO request does not meet security requirements", e);
208 ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
209 loginContext.setRelyingParty(requestContext.getInboundMessageIssuer());
210 loginContext.setSpAssertionConsumerService(requestContext.getSpAssertionConsumerService());
211 loginContext.setSpTarget(requestContext.getRelayState());
212 loginContext.setAuthenticationEngineURL(authenticationManagerPath);
213 loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
214 requestContext.setLoginContext(loginContext);
216 return requestContext;
220 * Creates a response to the Shibboleth SSO and sends the user, with response in tow, back to the relying party
221 * after they've been authenticated.
223 * @param inTransport inbound message transport
224 * @param outTransport outbound message transport
226 * @throws ProfileException thrown if the response can not be created and sent back to the relying party
228 protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
229 throws ProfileException {
230 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
231 ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) httpRequest
232 .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
234 ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
236 Response samlResponse;
238 if (loginContext.getAuthenticationFailure() != null) {
239 log.error("User authentication failed with the following error: {}", loginContext
240 .getAuthenticationFailure().toString());
241 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "User failed authentication"));
242 throw new ProfileException("Authentication failure", loginContext.getAuthenticationFailure());
245 resolveAttributes(requestContext);
247 ArrayList<Statement> statements = new ArrayList<Statement>();
248 statements.add(buildAuthenticationStatement(requestContext));
249 if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
250 AttributeStatement attributeStatement = buildAttributeStatement(requestContext,
251 "urn:oasis:names:tc:SAML:1.0:cm:bearer");
252 if (attributeStatement != null) {
253 requestContext.setRequestedAttributes(requestContext.getAttributes().keySet());
254 statements.add(attributeStatement);
258 samlResponse = buildResponse(requestContext, statements);
259 } catch (ProfileException e) {
260 samlResponse = buildErrorResponse(requestContext);
263 requestContext.setOutboundSAMLMessage(samlResponse);
264 requestContext.setOutboundSAMLMessageId(samlResponse.getID());
265 requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
266 encodeResponse(requestContext);
267 writeAuditLogEntry(requestContext);
271 * Creates an authentication request context from the current environmental information.
273 * @param loginContext current login context
274 * @param in inbound transport
275 * @param out outbount transport
277 * @return created authentication request context
279 * @throws ProfileException thrown if there is a problem creating the context
281 protected ShibbolethSSORequestContext buildRequestContext(ShibbolethSSOLoginContext loginContext,
282 HTTPInTransport in, HTTPOutTransport out) throws ProfileException {
283 ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
285 requestContext.setMessageDecoder(getMessageDecoders().get(getInboundBinding()));
287 requestContext.setLoginContext(loginContext);
288 requestContext.setRelayState(loginContext.getSpTarget());
290 requestContext.setInboundMessageTransport(in);
291 requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
293 requestContext.setOutboundMessageTransport(out);
294 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
296 requestContext.setMetadataProvider(getMetadataProvider());
298 String relyingPartyId = loginContext.getRelyingPartyId();
299 requestContext.setPeerEntityId(relyingPartyId);
300 requestContext.setInboundMessageIssuer(relyingPartyId);
302 populateRequestContext(requestContext);
304 return requestContext;
308 protected void populateRelyingPartyInformation(BaseSAMLProfileRequestContext requestContext)
309 throws ProfileException {
310 super.populateRelyingPartyInformation(requestContext);
312 EntityDescriptor relyingPartyMetadata = requestContext.getPeerEntityMetadata();
313 if (relyingPartyMetadata != null) {
314 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
315 requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML11P_NS));
320 protected void populateAssertingPartyInformation(BaseSAMLProfileRequestContext requestContext)
321 throws ProfileException {
322 super.populateAssertingPartyInformation(requestContext);
324 EntityDescriptor localEntityDescriptor = requestContext.getLocalEntityMetadata();
325 if (localEntityDescriptor != null) {
326 requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
327 requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
328 .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
333 protected void populateSAMLMessageInformation(BaseSAMLProfileRequestContext requestContext) throws ProfileException {
334 // nothing to do here
338 * Selects the appropriate endpoint for the relying party and stores it in the request context.
340 * @param requestContext current request context
342 * @return Endpoint selected from the information provided in the request context
344 protected Endpoint selectEndpoint(BaseSAMLProfileRequestContext requestContext) {
345 ShibbolethSSOLoginContext loginContext = ((ShibbolethSSORequestContext) requestContext).getLoginContext();
347 ShibbolethSSOEndpointSelector endpointSelector = new ShibbolethSSOEndpointSelector();
348 endpointSelector.setSpAssertionConsumerService(loginContext.getSpAssertionConsumerService());
349 endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
350 endpointSelector.setMetadataProvider(getMetadataProvider());
351 endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
352 endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
353 endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
354 endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
356 Endpoint endpoint = endpointSelector.selectEndpoint();
357 if (endpoint == null && loginContext.getSpAssertionConsumerService() != null) {
358 endpoint = endpointBuilder.buildObject();
359 endpoint.setLocation(loginContext.getSpAssertionConsumerService());
360 endpoint.setBinding(getInboundBinding());
361 log.warn("No endpoint available for relying party {}. Generating endpoint with ACS url {} and binding {}",
362 new Object[] { requestContext.getPeerEntityId(), endpoint.getLocation(), endpoint.getBinding() });
369 * Builds the authentication statement for the authenticated principal.
371 * @param requestContext current request context
373 * @return the created statement
375 * @throws ProfileException thrown if the authentication statement can not be created
377 protected AuthenticationStatement buildAuthenticationStatement(ShibbolethSSORequestContext requestContext)
378 throws ProfileException {
379 ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
381 AuthenticationStatement statement = authnStatementBuilder.buildObject();
382 statement.setAuthenticationInstant(loginContext.getAuthenticationInstant());
383 statement.setAuthenticationMethod(loginContext.getAuthenticationMethod());
385 statement.setSubjectLocality(buildSubjectLocality(requestContext));
387 Subject statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:bearer");
388 statement.setSubject(statementSubject);
394 * Constructs the subject locality for the authentication statement.
396 * @param requestContext curent request context
398 * @return subject locality for the authentication statement
400 protected SubjectLocality buildSubjectLocality(ShibbolethSSORequestContext requestContext) {
401 SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
403 HTTPInTransport inTransport = (HTTPInTransport) requestContext.getInboundMessageTransport();
404 subjectLocality.setIPAddress(inTransport.getPeerAddress());
406 return subjectLocality;
409 /** Represents the internal state of a Shibboleth SSO Request while it's being processed by the IdP. */
410 public class ShibbolethSSORequestContext extends
411 BaseSAML1ProfileRequestContext<Request, Response, ShibbolethSSOConfiguration> {
413 /** SP-provide assertion consumer service URL. */
414 private String spAssertionConsumerService;
416 /** Current login context. */
417 private ShibbolethSSOLoginContext loginContext;
420 * Gets the current login context.
422 * @return current login context
424 public ShibbolethSSOLoginContext getLoginContext() {
429 * Sets the current login context.
431 * @param context current login context
433 public void setLoginContext(ShibbolethSSOLoginContext context) {
434 loginContext = context;
438 * Gets the SP-provided assertion consumer service URL.
440 * @return SP-provided assertion consumer service URL
442 public String getSpAssertionConsumerService() {
443 return spAssertionConsumerService;
447 * Sets the SP-provided assertion consumer service URL.
449 * @param acs SP-provided assertion consumer service URL
451 public void setSpAssertionConsumerService(String acs) {
452 spAssertionConsumerService = acs;