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 /** URL of the authentication manager servlet. */
76 private String authenticationManagerPath;
81 * @param authnManagerPath path to the authentication manager servlet
83 * @throws IllegalArgumentException thrown if either the authentication manager path or encoding binding URI are
86 public ShibbolethSSOProfileHandler(String authnManagerPath) {
87 if (DatatypeHelper.isEmpty(authnManagerPath)) {
88 throw new IllegalArgumentException("Authentication manager path may not be null");
90 authenticationManagerPath = authnManagerPath;
92 authnStatementBuilder = (SAMLObjectBuilder<AuthenticationStatement>) getBuilderFactory().getBuilder(
93 AuthenticationStatement.DEFAULT_ELEMENT_NAME);
95 subjectLocalityBuilder = (SAMLObjectBuilder<SubjectLocality>) getBuilderFactory().getBuilder(
96 SubjectLocality.DEFAULT_ELEMENT_NAME);
100 public String getProfileId() {
101 return ShibbolethSSOConfiguration.PROFILE_ID;
105 public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
106 log.debug("Processing incoming request");
108 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
109 LoginContext loginContext = (LoginContext) httpRequest.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
111 if (loginContext == null) {
112 log.debug("Incoming request does not contain a login context, processing as first leg of request");
113 performAuthentication(inTransport, outTransport);
115 log.debug("Incoming request contains a login context, processing as second leg of request");
116 completeAuthenticationRequest(inTransport, outTransport);
121 * Creates a {@link LoginContext} an sends the request off to the AuthenticationManager to begin the process of
122 * authenticating the user.
124 * @param inTransport inbound message transport
125 * @param outTransport outbound message transport
127 * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
128 * authentication manager
130 protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
131 throws ProfileException {
133 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
134 HttpServletResponse httpResponse = ((HttpServletResponseAdapter) outTransport).getWrappedResponse();
136 ShibbolethSSORequestContext requestContext = decodeRequest(inTransport, outTransport);
137 ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
139 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(loginContext.getRelyingPartyId());
140 ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID);
141 if (ssoConfig == null) {
142 log.error("Shibboleth SSO profile is not configured for relying party " + loginContext.getRelyingPartyId());
143 throw new ProfileException("Shibboleth SSO profile is not configured for relying party "
144 + loginContext.getRelyingPartyId());
146 loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
148 httpRequest.setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
151 RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
152 dispatcher.forward(httpRequest, httpResponse);
154 } catch (IOException ex) {
155 log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
156 throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
157 } catch (ServletException ex) {
158 log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
159 throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
164 * Decodes an incoming request and populates a created request context with the resultant information.
166 * @param inTransport inbound message transport
167 * @param outTransport outbound message transport
169 * @return the created request context
171 * @throws ProfileException throw if there is a problem decoding the request
173 protected ShibbolethSSORequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
174 throws ProfileException {
175 log.debug("Decoding message with decoder binding {}", getInboundBinding());
177 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
179 ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
180 requestContext.setMetadataProvider(getMetadataProvider());
181 requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
183 requestContext.setCommunicationProfileId(ShibbolethSSOConfiguration.PROFILE_ID);
184 requestContext.setInboundMessageTransport(inTransport);
185 requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
186 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
188 requestContext.setOutboundMessageTransport(outTransport);
189 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML11P_NS);
191 SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
192 requestContext.setMessageDecoder(decoder);
194 decoder.decode(requestContext);
195 } catch (MessageDecodingException e) {
196 log.error("Error decoding Shibboleth SSO request", e);
197 throw new ProfileException("Error decoding Shibboleth SSO request", e);
198 } catch (SecurityException e) {
199 log.error("Shibboleth SSO request does not meet security requirements", e);
200 throw new ProfileException("Shibboleth SSO request does not meet security requirements", e);
203 ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
204 loginContext.setRelyingParty(requestContext.getInboundMessageIssuer());
205 loginContext.setSpAssertionConsumerService(requestContext.getSpAssertionConsumerService());
206 loginContext.setSpTarget(requestContext.getRelayState());
207 loginContext.setAuthenticationEngineURL(authenticationManagerPath);
208 loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
210 requestContext.setLoginContext(loginContext);
212 return requestContext;
216 * Creates a response to the Shibboleth SSO and sends the user, with response in tow, back to the relying party
217 * after they've been authenticated.
219 * @param inTransport inbound message transport
220 * @param outTransport outbound message transport
222 * @throws ProfileException thrown if the response can not be created and sent back to the relying party
224 protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
225 throws ProfileException {
226 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
227 ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) httpRequest
228 .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
230 ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
232 Response samlResponse;
234 if (loginContext.getAuthenticationFailure() != null) {
235 log.error("User authentication failed with the following error: {}", loginContext
236 .getAuthenticationFailure().toString());
237 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "User failed authentication"));
238 throw new ProfileException("Authentication failure", loginContext.getAuthenticationFailure());
241 resolveAttributes(requestContext);
243 ArrayList<Statement> statements = new ArrayList<Statement>();
244 statements.add(buildAuthenticationStatement(requestContext));
245 if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
246 AttributeStatement attributeStatement = buildAttributeStatement(requestContext,
247 "urn:oasis:names:tc:SAML:1.0:cm:bearer");
248 if (attributeStatement != null) {
249 requestContext.setRequestedAttributes(requestContext.getAttributes().keySet());
250 statements.add(attributeStatement);
254 samlResponse = buildResponse(requestContext, statements);
255 } catch (ProfileException e) {
256 samlResponse = buildErrorResponse(requestContext);
259 requestContext.setOutboundSAMLMessage(samlResponse);
260 requestContext.setOutboundSAMLMessageId(samlResponse.getID());
261 requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
262 encodeResponse(requestContext);
263 writeAuditLogEntry(requestContext);
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 ShibbolethSSORequestContext buildRequestContext(ShibbolethSSOLoginContext loginContext,
278 HTTPInTransport in, HTTPOutTransport out) throws ProfileException {
279 ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
281 requestContext.setMessageDecoder(getMessageDecoders().get(getInboundBinding()));
283 requestContext.setLoginContext(loginContext);
284 requestContext.setRelayState(loginContext.getSpTarget());
286 requestContext.setInboundMessageTransport(in);
287 requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
289 requestContext.setOutboundMessageTransport(out);
290 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
292 requestContext.setMetadataProvider(getMetadataProvider());
294 String relyingPartyId = loginContext.getRelyingPartyId();
295 requestContext.setPeerEntityId(relyingPartyId);
296 requestContext.setInboundMessageIssuer(relyingPartyId);
298 populateRequestContext(requestContext);
300 return requestContext;
304 protected void populateRelyingPartyInformation(BaseSAMLProfileRequestContext requestContext)
305 throws ProfileException {
306 super.populateRelyingPartyInformation(requestContext);
308 EntityDescriptor relyingPartyMetadata = requestContext.getPeerEntityMetadata();
309 if (relyingPartyMetadata != null) {
310 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
311 requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML11P_NS));
316 protected void populateAssertingPartyInformation(BaseSAMLProfileRequestContext requestContext)
317 throws ProfileException {
318 super.populateAssertingPartyInformation(requestContext);
320 EntityDescriptor localEntityDescriptor = requestContext.getLocalEntityMetadata();
321 if (localEntityDescriptor != null) {
322 requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
323 requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
324 .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
329 protected void populateSAMLMessageInformation(BaseSAMLProfileRequestContext requestContext)
330 throws ProfileException {
331 // nothing to do here
335 * Selects the appropriate endpoint for the relying party and stores it in the request context.
337 * @param requestContext current request context
339 * @return Endpoint selected from the information provided in the request context
341 protected Endpoint selectEndpoint(BaseSAMLProfileRequestContext requestContext) {
342 ShibbolethSSOLoginContext loginContext = ((ShibbolethSSORequestContext) requestContext).getLoginContext();
344 ShibbolethSSOEndpointSelector endpointSelector = new ShibbolethSSOEndpointSelector();
345 endpointSelector.setSpAssertionConsumerService(loginContext.getSpAssertionConsumerService());
346 endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
347 endpointSelector.setMetadataProvider(getMetadataProvider());
348 endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
349 endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
350 endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
351 endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
353 return endpointSelector.selectEndpoint();
357 * Builds the authentication statement for the authenticated principal.
359 * @param requestContext current request context
361 * @return the created statement
363 * @throws ProfileException thrown if the authentication statement can not be created
365 protected AuthenticationStatement buildAuthenticationStatement(ShibbolethSSORequestContext requestContext)
366 throws ProfileException {
367 ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
369 AuthenticationStatement statement = authnStatementBuilder.buildObject();
370 statement.setAuthenticationInstant(loginContext.getAuthenticationInstant());
371 statement.setAuthenticationMethod(loginContext.getAuthenticationMethod());
373 statement.setSubjectLocality(buildSubjectLocality(requestContext));
375 Subject statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:bearer");
376 statement.setSubject(statementSubject);
382 * Constructs the subject locality for the authentication statement.
384 * @param requestContext curent request context
386 * @return subject locality for the authentication statement
388 protected SubjectLocality buildSubjectLocality(ShibbolethSSORequestContext requestContext) {
389 SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
391 HTTPInTransport inTransport = (HTTPInTransport) requestContext.getInboundMessageTransport();
392 subjectLocality.setIPAddress(inTransport.getPeerAddress());
394 return subjectLocality;
397 /** Represents the internal state of a Shibboleth SSO Request while it's being processed by the IdP. */
398 public class ShibbolethSSORequestContext extends
399 BaseSAML1ProfileRequestContext<Request, Response, ShibbolethSSOConfiguration> {
401 /** SP-provide assertion consumer service URL. */
402 private String spAssertionConsumerService;
404 /** Current login context. */
405 private ShibbolethSSOLoginContext loginContext;
408 * Gets the current login context.
410 * @return current login context
412 public ShibbolethSSOLoginContext getLoginContext() {
417 * Sets the current login context.
419 * @param context current login context
421 public void setLoginContext(ShibbolethSSOLoginContext context) {
422 loginContext = context;
426 * Gets the SP-provided assertion consumer service URL.
428 * @return SP-provided assertion consumer service URL
430 public String getSpAssertionConsumerService() {
431 return spAssertionConsumerService;
435 * Sets the SP-provided assertion consumer service URL.
437 * @param acs SP-provided assertion consumer service URL
439 public void setSpAssertionConsumerService(String acs) {
440 spAssertionConsumerService = acs;