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.saml2.metadata.provider.MetadataProvider;
44 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
45 import org.opensaml.ws.message.decoder.MessageDecodingException;
46 import org.opensaml.ws.transport.http.HTTPInTransport;
47 import org.opensaml.ws.transport.http.HTTPOutTransport;
48 import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
49 import org.opensaml.ws.transport.http.HttpServletResponseAdapter;
50 import org.opensaml.xml.security.SecurityException;
51 import org.opensaml.xml.util.DatatypeHelper;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
55 import edu.internet2.middleware.shibboleth.common.ShibbolethConstants;
56 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
57 import edu.internet2.middleware.shibboleth.common.relyingparty.ProfileConfiguration;
58 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
59 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml1.ShibbolethSSOConfiguration;
60 import edu.internet2.middleware.shibboleth.common.util.HttpHelper;
61 import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
62 import edu.internet2.middleware.shibboleth.idp.authn.ShibbolethSSOLoginContext;
64 /** Shibboleth SSO request profile handler. */
65 public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
68 private final Logger log = LoggerFactory.getLogger(ShibbolethSSOProfileHandler.class);
70 /** Builder of AuthenticationStatement objects. */
71 private SAMLObjectBuilder<AuthenticationStatement> authnStatementBuilder;
73 /** Builder of SubjectLocality objects. */
74 private SAMLObjectBuilder<SubjectLocality> subjectLocalityBuilder;
76 /** URL of the authentication manager servlet. */
77 private String authenticationManagerPath;
82 * @param authnManagerPath path to the authentication manager servlet
84 * @throws IllegalArgumentException thrown if either the authentication manager path or encoding binding URI are
87 public ShibbolethSSOProfileHandler(String authnManagerPath) {
88 if (DatatypeHelper.isEmpty(authnManagerPath)) {
89 throw new IllegalArgumentException("Authentication manager path may not be null");
91 authenticationManagerPath = authnManagerPath;
93 authnStatementBuilder = (SAMLObjectBuilder<AuthenticationStatement>) getBuilderFactory().getBuilder(
94 AuthenticationStatement.DEFAULT_ELEMENT_NAME);
96 subjectLocalityBuilder = (SAMLObjectBuilder<SubjectLocality>) getBuilderFactory().getBuilder(
97 SubjectLocality.DEFAULT_ELEMENT_NAME);
101 public String getProfileId() {
102 return "urn:mace:shibboleth:2.0:idp:profiles:shibboleth:request:sso";
106 public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
107 log.debug("Processing incoming request");
109 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
110 LoginContext loginContext = (LoginContext) httpRequest.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
112 if (loginContext == null) {
113 log.debug("Incoming request does not contain a login context, processing as first leg of request");
114 performAuthentication(inTransport, outTransport);
116 log.debug("Incoming request contains a login context, processing as second leg of request");
117 completeAuthenticationRequest(inTransport, outTransport);
122 * Creates a {@link LoginContext} an sends the request off to the AuthenticationManager to begin the process of
123 * authenticating the user.
125 * @param inTransport inbound message transport
126 * @param outTransport outbound message transport
128 * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
129 * authentication manager
131 protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
132 throws ProfileException {
134 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
135 HttpServletResponse httpResponse = ((HttpServletResponseAdapter) outTransport).getWrappedResponse();
137 ShibbolethSSORequestContext requestContext = decodeRequest(inTransport, outTransport);
138 ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
140 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(loginContext.getRelyingPartyId());
141 ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID);
142 if (ssoConfig == null) {
143 log.error("Shibboleth SSO profile is not configured for relying party " + loginContext.getRelyingPartyId());
144 throw new ProfileException("Shibboleth SSO profile is not configured for relying party "
145 + loginContext.getRelyingPartyId());
147 loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
149 httpRequest.setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
152 RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
153 dispatcher.forward(httpRequest, httpResponse);
155 } catch (IOException ex) {
156 log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
157 throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
158 } catch (ServletException ex) {
159 log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
160 throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
165 * Decodes an incoming request and populates a created request context with the resultant information.
167 * @param inTransport inbound message transport
168 * @param outTransport outbound message transport
170 * @return the created request context
172 * @throws ProfileException throw if there is a problem decoding the request
174 protected ShibbolethSSORequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
175 throws ProfileException {
176 log.debug("Decoding message with decoder binding {}", getInboundBinding());
178 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
180 ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
181 requestContext.setMetadataProvider(getMetadataProvider());
182 requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
184 requestContext.setCommunicationProfileId(ShibbolethSSOConfiguration.PROFILE_ID);
185 requestContext.setInboundMessageTransport(inTransport);
186 requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
187 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
189 requestContext.setOutboundMessageTransport(outTransport);
190 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML11P_NS);
192 SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
193 requestContext.setMessageDecoder(decoder);
195 decoder.decode(requestContext);
196 } catch (MessageDecodingException e) {
197 log.error("Error decoding Shibboleth SSO request", e);
198 throw new ProfileException("Error decoding Shibboleth SSO request", e);
199 } catch (SecurityException e) {
200 log.error("Shibboleth SSO request does not meet security requirements", e);
201 throw new ProfileException("Shibboleth SSO request does not meet security requirements", e);
204 ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
205 loginContext.setRelyingParty(requestContext.getInboundMessageIssuer());
206 loginContext.setSpAssertionConsumerService(requestContext.getSpAssertionConsumerService());
207 loginContext.setSpTarget(requestContext.getRelayState());
208 loginContext.setAuthenticationEngineURL(authenticationManagerPath);
209 loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
211 requestContext.setLoginContext(loginContext);
213 return requestContext;
217 * Creates a response to the Shibboleth SSO and sends the user, with response in tow, back to the relying party
218 * after they've been authenticated.
220 * @param inTransport inbound message transport
221 * @param outTransport outbound message transport
223 * @throws ProfileException thrown if the response can not be created and sent back to the relying party
225 protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
226 throws ProfileException {
227 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
228 ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) httpRequest
229 .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
231 ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
233 Response samlResponse;
235 if (loginContext.getAuthenticationFailure() != null) {
236 log.error("User authentication failed with the following error: {}", loginContext
237 .getAuthenticationFailure().toString());
238 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "User failed authentication"));
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.getPrincipalAttributes().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.setPrincipalName(loginContext.getPrincipalName());
285 requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
286 requestContext.setUserSession(getUserSession(in));
287 requestContext.setRelayState(loginContext.getSpTarget());
289 requestContext.setInboundMessageTransport(in);
290 requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
292 requestContext.setOutboundMessageTransport(out);
293 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
295 MetadataProvider metadataProvider = getMetadataProvider();
296 requestContext.setMetadataProvider(metadataProvider);
298 String relyingPartyId = loginContext.getRelyingPartyId();
299 requestContext.setInboundMessageIssuer(relyingPartyId);
302 EntityDescriptor relyingPartyMetadata = metadataProvider.getEntityDescriptor(relyingPartyId);
303 if (relyingPartyMetadata != null) {
304 requestContext.setPeerEntityMetadata(relyingPartyMetadata);
305 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
306 requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata
307 .getSPSSODescriptor(SAMLConstants.SAML11P_NS));
309 } catch (MetadataProviderException e) {
310 log.error("Unable to locate metadata for relying party");
311 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
312 "Error locating relying party metadata"));
313 throw new ProfileException("Error locating relying party metadata");
316 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
317 if (rpConfig == null) {
318 log.error("Unable to retrieve relying party configuration data for entity with ID {}", relyingPartyId);
319 throw new ProfileException("Unable to retrieve relying party configuration data for entity with ID "
322 requestContext.setRelyingPartyConfiguration(rpConfig);
324 ShibbolethSSOConfiguration profileConfig = (ShibbolethSSOConfiguration) rpConfig
325 .getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID);
326 requestContext.setProfileConfiguration(profileConfig);
327 requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
328 requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
330 String assertingPartyId = rpConfig.getProviderId();
331 requestContext.setLocalEntityId(assertingPartyId);
332 requestContext.setOutboundMessageIssuer(assertingPartyId);
334 EntityDescriptor localEntityDescriptor = metadataProvider.getEntityDescriptor(assertingPartyId);
335 if (localEntityDescriptor != null) {
336 requestContext.setLocalEntityMetadata(localEntityDescriptor);
337 requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
338 requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
339 .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
341 } catch (MetadataProviderException e) {
342 log.error("Unable to locate metadata for asserting party");
343 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
344 "Error locating asserting party metadata"));
345 throw new ProfileException("Error locating asserting party metadata");
348 return requestContext;
352 * Selects the appropriate endpoint for the relying party and stores it in the request context.
354 * @param requestContext current request context
356 * @return Endpoint selected from the information provided in the request context
358 protected Endpoint selectEndpoint(ShibbolethSSORequestContext requestContext) {
359 ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
361 ShibbolethSSOEndpointSelector endpointSelector = new ShibbolethSSOEndpointSelector();
362 endpointSelector.setSpAssertionConsumerService(loginContext.getSpAssertionConsumerService());
363 endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
364 endpointSelector.setMetadataProvider(getMetadataProvider());
365 endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
366 endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
367 endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
368 endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
370 return endpointSelector.selectEndpoint();
374 * Builds the authentication statement for the authenticated principal.
376 * @param requestContext current request context
378 * @return the created statement
380 * @throws ProfileException thrown if the authentication statement can not be created
382 protected AuthenticationStatement buildAuthenticationStatement(ShibbolethSSORequestContext requestContext)
383 throws ProfileException {
384 ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
386 AuthenticationStatement statement = authnStatementBuilder.buildObject();
387 statement.setAuthenticationInstant(loginContext.getAuthenticationInstant());
388 statement.setAuthenticationMethod(loginContext.getAuthenticationMethod());
390 statement.setSubjectLocality(buildSubjectLocality(requestContext));
392 Subject statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:bearer");
393 statement.setSubject(statementSubject);
399 * Constructs the subject locality for the authentication statement.
401 * @param requestContext curent request context
403 * @return subject locality for the authentication statement
405 protected SubjectLocality buildSubjectLocality(ShibbolethSSORequestContext requestContext) {
406 SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
408 HTTPInTransport inTransport = (HTTPInTransport) requestContext.getInboundMessageTransport();
409 subjectLocality.setIPAddress(inTransport.getPeerAddress());
410 subjectLocality.setDNSAddress(inTransport.getPeerDomainName());
412 return subjectLocality;
415 /** Represents the internal state of a Shibboleth SSO Request while it's being processed by the IdP. */
416 public class ShibbolethSSORequestContext extends
417 BaseSAML1ProfileRequestContext<Request, Response, ShibbolethSSOConfiguration> {
419 /** SP-provide assertion consumer service URL. */
420 private String spAssertionConsumerService;
422 /** Current login context. */
423 private ShibbolethSSOLoginContext loginContext;
426 * Gets the current login context.
428 * @return current login context
430 public ShibbolethSSOLoginContext getLoginContext() {
435 * Sets the current login context.
437 * @param context current login context
439 public void setLoginContext(ShibbolethSSOLoginContext context) {
440 loginContext = context;
444 * Gets the SP-provided assertion consumer service URL.
446 * @return SP-provided assertion consumer service URL
448 public String getSpAssertionConsumerService() {
449 return spAssertionConsumerService;
453 * Sets the SP-provided assertion consumer service URL.
455 * @param acs SP-provided assertion consumer service URL
457 public void setSpAssertionConsumerService(String acs) {
458 spAssertionConsumerService = acs;