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.io.UnsupportedEncodingException;
21 import java.net.URLDecoder;
22 import java.util.ArrayList;
23 import java.util.List;
25 import javax.servlet.RequestDispatcher;
26 import javax.servlet.ServletException;
27 import javax.servlet.ServletRequest;
28 import javax.servlet.ServletResponse;
29 import javax.servlet.http.HttpServletRequest;
30 import javax.servlet.http.HttpServletResponse;
31 import javax.servlet.http.HttpSession;
33 import org.apache.log4j.Logger;
34 import org.opensaml.common.SAMLObjectBuilder;
35 import org.opensaml.common.binding.BasicEndpointSelector;
36 import org.opensaml.common.binding.BindingException;
37 import org.opensaml.common.binding.encoding.MessageEncoder;
38 import org.opensaml.saml1.core.AttributeStatement;
39 import org.opensaml.saml1.core.AuthenticationStatement;
40 import org.opensaml.saml1.core.Request;
41 import org.opensaml.saml1.core.Response;
42 import org.opensaml.saml1.core.Statement;
43 import org.opensaml.saml1.core.StatusCode;
44 import org.opensaml.saml1.core.Subject;
45 import org.opensaml.saml1.core.SubjectLocality;
46 import org.opensaml.saml2.metadata.AssertionConsumerService;
47 import org.opensaml.saml2.metadata.Endpoint;
48 import org.opensaml.saml2.metadata.RoleDescriptor;
49 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
50 import org.opensaml.xml.util.DatatypeHelper;
52 import edu.internet2.middleware.shibboleth.common.ShibbolethConstants;
53 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
54 import edu.internet2.middleware.shibboleth.common.profile.ProfileRequest;
55 import edu.internet2.middleware.shibboleth.common.profile.ProfileResponse;
56 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
57 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml1.ShibbolethSSOConfiguration;
58 import edu.internet2.middleware.shibboleth.common.util.HttpHelper;
59 import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
60 import edu.internet2.middleware.shibboleth.idp.authn.ShibbolethSSOLoginContext;
62 /** Shibboleth SSO request profile handler. */
63 public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
66 private final Logger log = Logger.getLogger(ShibbolethSSOProfileHandler.class);
68 /** Builder of AuthenticationStatement objects. */
69 private SAMLObjectBuilder<AuthenticationStatement> authnStatementBuilder;
71 /** Builder of SubjectLocality objects. */
72 private SAMLObjectBuilder<SubjectLocality> subjectLocalityBuilder;
74 /** URL of the authentication manager servlet. */
75 private String authenticationManagerPath;
77 /** URI of SAML 1 bindings supported for outgoing message encoding. */
78 private ArrayList<String> supportedOutgoingBindings;
83 * @param authnManagerPath path to the authentication manager servlet
84 * @param outgoingBindings URIs of SAML 1 bindings supported for outgoing message encoding
86 * @throws IllegalArgumentException thrown if either the authentication manager path or encoding binding URI are
89 public ShibbolethSSOProfileHandler(String authnManagerPath, List<String> outgoingBindings) {
90 if (DatatypeHelper.isEmpty(authnManagerPath)) {
91 throw new IllegalArgumentException("Authentication manager path may not be null");
93 authenticationManagerPath = authnManagerPath;
95 if(outgoingBindings == null || outgoingBindings.isEmpty()){
96 throw new IllegalArgumentException("List of supported outgoing bindings may not be empty");
98 supportedOutgoingBindings = new ArrayList<String>(outgoingBindings);
100 authnStatementBuilder = (SAMLObjectBuilder<AuthenticationStatement>) getBuilderFactory().getBuilder(
101 AuthenticationStatement.DEFAULT_ELEMENT_NAME);
103 subjectLocalityBuilder = (SAMLObjectBuilder<SubjectLocality>) getBuilderFactory().getBuilder(
104 SubjectLocality.DEFAULT_ELEMENT_NAME);
108 public String getProfileId() {
109 return "urn:mace:shibboleth:2.0:idp:profiles:shibboleth:request:sso";
113 public void processRequest(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response)
114 throws ProfileException {
116 if (response.getRawResponse().isCommitted()) {
117 log.error("HTTP Response already committed");
120 if (log.isDebugEnabled()) {
121 log.debug("Processing incomming request");
123 HttpSession httpSession = ((HttpServletRequest) request.getRawRequest()).getSession(true);
124 if (httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY) == null) {
125 if (log.isDebugEnabled()) {
126 log.debug("User session does not contain a login context, processing as first leg of request");
128 performAuthentication(request, response);
130 if (log.isDebugEnabled()) {
131 log.debug("User session contains a login context, processing as second leg of request");
133 completeAuthenticationRequest(request, response);
138 * Creates a {@link LoginContext} an sends the request off to the AuthenticationManager to begin the process of
139 * authenticating the user.
141 * @param request current request
142 * @param response current response
144 * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
145 * authentication manager
147 protected void performAuthentication(ProfileRequest<ServletRequest> request,
148 ProfileResponse<ServletResponse> response) throws ProfileException {
150 HttpServletRequest httpRequest = (HttpServletRequest) request.getRawRequest();
151 HttpServletResponse httpResponse = (HttpServletResponse) response.getRawResponse();
152 HttpSession httpSession = httpRequest.getSession(true);
154 LoginContext loginContext = buildLoginContext(httpRequest);
155 if (getRelyingPartyConfiguration(loginContext.getRelyingPartyId()) == null) {
156 log.error("Shibboleth SSO profile is not configured for relying party " + loginContext.getRelyingPartyId());
157 throw new ProfileException("Shibboleth SSO profile is not configured for relying party "
158 + loginContext.getRelyingPartyId());
161 httpSession.setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
164 RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
165 dispatcher.forward(httpRequest, httpResponse);
167 } catch (IOException ex) {
168 log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
169 throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
170 } catch (ServletException ex) {
171 log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
172 throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
177 * Creates a response to the Shibboleth SSO and sends the user, with response in tow, back to the relying party
178 * after they've been authenticated.
180 * @param request current request
181 * @param response current response
183 * @throws ProfileException thrown if the response can not be created and sent back to the relying party
185 protected void completeAuthenticationRequest(ProfileRequest<ServletRequest> request,
186 ProfileResponse<ServletResponse> response) throws ProfileException {
187 HttpSession httpSession = ((HttpServletRequest) request.getRawRequest()).getSession(true);
189 ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) httpSession
190 .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
191 httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
193 ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, request, response);
195 Response samlResponse;
197 if (loginContext.getPrincipalName() == null) {
198 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "User failed authentication"));
199 throw new ProfileException("User failed authentication");
202 AuthenticationStatement authnStatement = buildAuthenticationStatement(requestContext);
203 AttributeStatement attributeStatement = buildAttributeStatement(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:bearer");
205 ArrayList<Statement> statements = new ArrayList<Statement>();
206 statements.add(authnStatement);
207 if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
208 statements.add(attributeStatement);
211 samlResponse = buildResponse(requestContext, statements);
212 } catch (ProfileException e) {
213 samlResponse = buildErrorResponse(requestContext);
216 requestContext.setSamlResponse(samlResponse);
217 encodeResponse(requestContext);
218 writeAuditLogEntry(requestContext);
222 * Creates a login context from the incoming HTTP request.
224 * @param request current HTTP request
226 * @return the constructed login context
228 * @throws ProfileException thrown if the incomming request did not contain a providerId, shire, and target
231 protected ShibbolethSSOLoginContext buildLoginContext(HttpServletRequest request) throws ProfileException {
232 ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
235 String providerId = DatatypeHelper.safeTrimOrNullString(request.getParameter("providerId"));
236 if (providerId == null) {
237 log.error("No providerId parameter in Shibboleth SSO request");
238 throw new ProfileException("No providerId parameter in Shibboleth SSO request");
240 loginContext.setRelyingParty(URLDecoder.decode(providerId, "UTF-8"));
242 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(providerId);
243 if (rpConfig == null) {
244 log.error("No relying party configuration available for " + providerId);
245 throw new ProfileException("No relying party configuration available for " + providerId);
247 loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
249 String acs = DatatypeHelper.safeTrimOrNullString(request.getParameter("shire"));
251 log.error("No shire parameter in Shibboleth SSO request");
252 throw new ProfileException("No shire parameter in Shibboleth SSO request");
254 loginContext.setSpAssertionConsumerService(URLDecoder.decode(acs, "UTF-8"));
256 String target = DatatypeHelper.safeTrimOrNullString(request.getParameter("target"));
257 if (target == null) {
258 log.error("No target parameter in Shibboleth SSO request");
259 throw new ProfileException("No target parameter in Shibboleth SSO request");
261 loginContext.setSpTarget(URLDecoder.decode(target, "UTF-8"));
262 } catch (UnsupportedEncodingException e) {
263 // UTF-8 encoding required to be supported by all JVMs.
266 loginContext.setAuthenticationEngineURL(authenticationManagerPath);
267 loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(request));
272 * Creates an authentication request context from the current environmental information.
274 * @param loginContext current login context
275 * @param request current request
276 * @param response current response
278 * @return created authentication request context
280 * @throws ProfileException thrown if asserting and relying party metadata can not be located
282 protected ShibbolethSSORequestContext buildRequestContext(ShibbolethSSOLoginContext loginContext,
283 ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response) throws ProfileException {
284 ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext(request, response);
286 requestContext.setLoginContext(loginContext);
288 requestContext.setPrincipalName(loginContext.getPrincipalName());
290 requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
292 String relyingPartyId = loginContext.getRelyingPartyId();
294 requestContext.setRelyingPartyId(relyingPartyId);
296 populateRelyingPartyData(requestContext);
298 populateAssertingPartyData(requestContext);
300 return requestContext;
304 * Populates the relying party entity and role metadata and relying party configuration data.
306 * @param requestContext current request context with relying party ID populated
308 * @throws ProfileException thrown if metadata can not be located for the relying party
310 protected void populateRelyingPartyData(ShibbolethSSORequestContext requestContext) throws ProfileException {
312 requestContext.setRelyingPartyMetadata(getMetadataProvider().getEntityDescriptor(
313 requestContext.getRelyingPartyId()));
315 RoleDescriptor relyingPartyRole = requestContext.getRelyingPartyMetadata().getSPSSODescriptor(
316 ShibbolethConstants.SAML11P_NS);
318 if (relyingPartyRole == null) {
319 relyingPartyRole = requestContext.getRelyingPartyMetadata().getSPSSODescriptor(
320 ShibbolethConstants.SAML10P_NS);
321 if (relyingPartyRole == null) {
322 throw new MetadataProviderException("Unable to locate SPSSO role descriptor for entity "
323 + requestContext.getRelyingPartyId());
326 requestContext.setRelyingPartyRoleMetadata(relyingPartyRole);
328 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(requestContext.getRelyingPartyId());
329 requestContext.setRelyingPartyConfiguration(rpConfig);
331 requestContext.setProfileConfiguration((ShibbolethSSOConfiguration) rpConfig
332 .getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID));
334 } catch (MetadataProviderException e) {
335 log.error("Unable to locate metadata for relying party " + requestContext.getRelyingPartyId());
336 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
337 "Unable to locate metadata for relying party " + requestContext.getRelyingPartyId()));
338 throw new ProfileException("Unable to locate metadata for relying party "
339 + requestContext.getRelyingPartyId());
344 * Populates the asserting party entity and role metadata.
346 * @param requestContext current request context with relying party configuration populated
348 * @throws ProfileException thrown if metadata can not be located for the asserting party
350 protected void populateAssertingPartyData(ShibbolethSSORequestContext requestContext) throws ProfileException {
351 String assertingPartyId = requestContext.getRelyingPartyConfiguration().getProviderId();
354 requestContext.setAssertingPartyId(assertingPartyId);
356 requestContext.setAssertingPartyMetadata(getMetadataProvider().getEntityDescriptor(assertingPartyId));
358 RoleDescriptor assertingPartyRole = requestContext.getAssertingPartyMetadata().getIDPSSODescriptor(
359 ShibbolethConstants.SHIB_SSO_PROFILE_URI);
360 if (assertingPartyRole == null) {
361 throw new MetadataProviderException("Unable to locate IDPSSO role descriptor for entity "
364 requestContext.setAssertingPartyRoleMetadata(assertingPartyRole);
365 } catch (MetadataProviderException e) {
366 log.error("Unable to locate metadata for asserting party " + assertingPartyId);
367 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
368 "Unable to locate metadata for relying party " + assertingPartyId));
369 throw new ProfileException("Unable to locate metadata for relying party " + assertingPartyId);
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 HttpServletRequest httpRequest = (HttpServletRequest) requestContext.getProfileRequest().getRawRequest();
409 subjectLocality.setIPAddress(httpRequest.getRemoteAddr());
410 subjectLocality.setDNSAddress(httpRequest.getRemoteHost());
412 return subjectLocality;
416 * Encodes the request's SAML response and writes it to the servlet response.
418 * @param requestContext current request context
420 * @throws ProfileException thrown if no message encoder is registered for this profiles binding
422 protected void encodeResponse(ShibbolethSSORequestContext requestContext) throws ProfileException {
423 if (log.isDebugEnabled()) {
424 log.debug("Encoding response to SAML request from relying party " + requestContext.getRelyingPartyId());
427 Endpoint relyingPartyEndpoint;
429 BasicEndpointSelector endpointSelector = new BasicEndpointSelector();
430 endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
431 endpointSelector.setMetadataProvider(getMetadataProvider());
432 endpointSelector.setRelyingParty(requestContext.getRelyingPartyMetadata());
433 endpointSelector.setRelyingPartyRole(requestContext.getRelyingPartyRoleMetadata());
434 endpointSelector.setSamlRequest(requestContext.getSamlRequest());
435 endpointSelector.getSupportedIssuerBindings().addAll(supportedOutgoingBindings);
436 relyingPartyEndpoint = endpointSelector.selectEndpoint();
438 if (relyingPartyEndpoint == null) {
439 log.error("Unable to determine endpoint, from metadata, for relying party "
440 + requestContext.getRelyingPartyId() + " acting in SPSSO role");
441 throw new ProfileException("Unable to determine endpoint, from metadata, for relying party "
442 + requestContext.getRelyingPartyId() + " acting in SPSSO role");
445 MessageEncoder<ServletResponse> encoder = getMessageEncoderFactory().getMessageEncoder(
446 relyingPartyEndpoint.getBinding());
447 encoder.setRelyingPartyEndpoint(relyingPartyEndpoint);
448 super.populateMessageEncoder(encoder);
449 encoder.setRelayState(requestContext.getLoginContext().getSpTarget());
450 ProfileResponse<ServletResponse> profileResponse = requestContext.getProfileResponse();
451 encoder.setResponse(profileResponse.getRawResponse());
452 encoder.setSamlMessage(requestContext.getSamlResponse());
453 requestContext.setMessageEncoder(encoder);
457 } catch (BindingException e) {
458 throw new ProfileException("Unable to encode response to relying party: "
459 + requestContext.getRelyingPartyId(), e);
463 /** Represents the internal state of a Shibboleth SSO Request while it's being processed by the IdP. */
464 protected class ShibbolethSSORequestContext extends
465 SAML1ProfileRequestContext<Request, Response, ShibbolethSSOConfiguration> {
467 /** Current login context. */
468 private ShibbolethSSOLoginContext loginContext;
473 * @param request current profile request
474 * @param response current profile response
476 public ShibbolethSSORequestContext(ProfileRequest<ServletRequest> request,
477 ProfileResponse<ServletResponse> response) {
478 super(request, response);
482 * Gets the current login context.
484 * @return current login context
486 public ShibbolethSSOLoginContext getLoginContext() {
491 * Sets the current login context.
493 * @param context current login context
495 public void setLoginContext(ShibbolethSSOLoginContext context) {
496 loginContext = context;