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;
24 import javax.servlet.RequestDispatcher;
25 import javax.servlet.ServletException;
26 import javax.servlet.ServletRequest;
27 import javax.servlet.ServletResponse;
28 import javax.servlet.http.HttpServletRequest;
29 import javax.servlet.http.HttpServletResponse;
30 import javax.servlet.http.HttpSession;
32 import org.apache.log4j.Logger;
33 import org.opensaml.common.SAMLObject;
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.common.xml.SAMLConstants;
39 import org.opensaml.saml1.core.AuthenticationStatement;
40 import org.opensaml.saml1.core.Response;
41 import org.opensaml.saml1.core.Statement;
42 import org.opensaml.saml1.core.StatusCode;
43 import org.opensaml.saml1.core.Subject;
44 import org.opensaml.saml2.metadata.AssertionConsumerService;
45 import org.opensaml.saml2.metadata.Endpoint;
46 import org.opensaml.saml2.metadata.RoleDescriptor;
47 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
48 import org.opensaml.xml.util.DatatypeHelper;
50 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
51 import edu.internet2.middleware.shibboleth.common.profile.ProfileRequest;
52 import edu.internet2.middleware.shibboleth.common.profile.ProfileResponse;
53 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
54 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml1.ShibbolethSSOConfiguration;
55 import edu.internet2.middleware.shibboleth.common.util.HttpHelper;
56 import edu.internet2.middleware.shibboleth.idp.ShibbolethConstants;
57 import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
58 import edu.internet2.middleware.shibboleth.idp.authn.ShibbolethSSOLoginContext;
60 /** Shibboleth SSO request profile handler. */
61 public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
64 private final Logger log = Logger.getLogger(ShibbolethSSOProfileHandler.class);
66 /** Builder of AuthenticationStatement objects. */
67 private SAMLObjectBuilder<AuthenticationStatement> authnStatementBuilder;
69 /** URL of the authentication manager servlet. */
70 private String authenticationManagerPath;
75 * @param authnManagerPath path to the authentication manager servlet
77 * @throws IllegalArgumentException thrown if either the authentication manager path or encoding binding URI are
80 public ShibbolethSSOProfileHandler(String authnManagerPath) {
81 if (DatatypeHelper.isEmpty(authnManagerPath)) {
82 throw new IllegalArgumentException("Authentication manager path may not be null");
85 authenticationManagerPath = authnManagerPath;
87 authnStatementBuilder = (SAMLObjectBuilder<AuthenticationStatement>) getBuilderFactory().getBuilder(
88 AuthenticationStatement.DEFAULT_ELEMENT_NAME);
92 * Convenience method for getting the SAML 1 AuthenticationStatement builder.
94 * @return SAML 1 AuthenticationStatement builder
96 public SAMLObjectBuilder<AuthenticationStatement> getAuthenticationStatementBuilder() {
97 return authnStatementBuilder;
101 public String getProfileId() {
102 return "urn:mace:shibboleth:2.0:idp:profiles:shibboleth:request:sso";
106 public void processRequest(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response)
107 throws ProfileException {
109 if (response.getRawResponse().isCommitted()) {
110 log.error("HTTP Response already committed");
113 if (log.isDebugEnabled()) {
114 log.debug("Processing incomming request");
116 HttpSession httpSession = ((HttpServletRequest) request.getRawRequest()).getSession(true);
117 if (httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY) == null) {
118 if (log.isDebugEnabled()) {
119 log.debug("User session does not contain a login context, processing as first leg of request");
121 performAuthentication(request, response);
123 if (log.isDebugEnabled()) {
124 log.debug("User session contains a login context, processing as second leg of request");
126 completeAuthenticationRequest(request, response);
131 * Creates a {@link LoginContext} an sends the request off to the AuthenticationManager to begin the process of
132 * authenticating the user.
134 * @param request current request
135 * @param response current response
137 * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
138 * authentication manager
140 protected void performAuthentication(ProfileRequest<ServletRequest> request,
141 ProfileResponse<ServletResponse> response) throws ProfileException {
143 HttpServletRequest httpRequest = (HttpServletRequest) request.getRawRequest();
144 HttpServletResponse httpResponse = (HttpServletResponse) response.getRawResponse();
145 HttpSession httpSession = httpRequest.getSession(true);
147 LoginContext loginContext = buildLoginContext(httpRequest);
148 if (getRelyingPartyConfiguration(loginContext.getRelyingPartyId()) == null) {
149 log.error("Shibboleth SSO profile is not configured for relying party " + loginContext.getRelyingPartyId());
150 throw new ProfileException("Shibboleth SSO profile is not configured for relying party "
151 + loginContext.getRelyingPartyId());
154 httpSession.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 * Creates a response to the Shibboleth SSO and sends the user, with response in tow, back to the relying party
171 * after they've been authenticated.
173 * @param request current request
174 * @param response current response
176 * @throws ProfileException thrown if the response can not be created and sent back to the relying party
178 protected void completeAuthenticationRequest(ProfileRequest<ServletRequest> request,
179 ProfileResponse<ServletResponse> response) throws ProfileException {
180 HttpSession httpSession = ((HttpServletRequest) request.getRawRequest()).getSession(true);
182 ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) httpSession
183 .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
184 httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
186 ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, request, response);
188 Response samlResponse;
190 if (!loginContext.isPrincipalAuthenticated()) {
191 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "User failed authentication"));
192 throw new ProfileException("User failed authentication");
195 ArrayList<Statement> statements = new ArrayList<Statement>();
196 statements.add(buildAuthenticationStatement(requestContext));
197 if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
199 .add(buildAttributeStatement(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches"));
202 samlResponse = buildResponse(requestContext, statements);
203 } catch (ProfileException e) {
204 samlResponse = buildErrorResponse(requestContext);
207 requestContext.setSamlResponse(samlResponse);
208 encodeResponse(requestContext);
209 writeAuditLogEntry(requestContext);
213 * Creates a login context from the incoming HTTP request.
215 * @param request current HTTP request
217 * @return the constructed login context
219 * @throws ProfileException thrown if the incomming request did not contain a providerId, shire, and target
222 protected ShibbolethSSOLoginContext buildLoginContext(HttpServletRequest request) throws ProfileException {
223 ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
226 String providerId = DatatypeHelper.safeTrimOrNullString(request.getParameter("providerId"));
227 if (providerId == null) {
228 log.error("No providerId parameter in Shibboleth SSO request");
229 throw new ProfileException("No providerId parameter in Shibboleth SSO request");
231 loginContext.setRelyingParty(URLDecoder.decode(providerId, "UTF-8"));
233 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(providerId);
234 if (rpConfig == null) {
235 log.error("No relying party configuration available for " + providerId);
236 throw new ProfileException("No relying party configuration available for " + providerId);
238 loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
240 String acs = DatatypeHelper.safeTrimOrNullString(request.getParameter("shire"));
242 log.error("No shire parameter in Shibboleth SSO request");
243 throw new ProfileException("No shire parameter in Shibboleth SSO request");
245 loginContext.setSpAssertionConsumerService(URLDecoder.decode(acs, "UTF-8"));
247 String target = DatatypeHelper.safeTrimOrNullString(request.getParameter("target"));
248 if (target == null) {
249 log.error("No target parameter in Shibboleth SSO request");
250 throw new ProfileException("No target parameter in Shibboleth SSO request");
252 loginContext.setSpTarget(URLDecoder.decode(target, "UTF-8"));
253 } catch (UnsupportedEncodingException e) {
254 // UTF-8 encoding required to be supported by all JVMs.
257 loginContext.setAuthenticationEngineURL(authenticationManagerPath);
258 loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(request));
263 * Creates an authentication request context from the current environmental information.
265 * @param loginContext current login context
266 * @param request current request
267 * @param response current response
269 * @return created authentication request context
271 * @throws ProfileException thrown if asserting and relying party metadata can not be located
273 protected ShibbolethSSORequestContext buildRequestContext(ShibbolethSSOLoginContext loginContext,
274 ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response) throws ProfileException {
275 ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext(request, response);
277 requestContext.setLoginContext(loginContext);
279 requestContext.setPrincipalName(loginContext.getPrincipalName());
281 requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
283 String relyingPartyId = loginContext.getRelyingPartyId();
285 requestContext.setRelyingPartyId(relyingPartyId);
287 populateRelyingPartyData(requestContext);
289 populateAssertingPartyData(requestContext);
291 return requestContext;
295 * Populates the relying party entity and role metadata and relying party configuration data.
297 * @param requestContext current request context with relying party ID populated
299 * @throws ProfileException thrown if metadata can not be located for the relying party
301 protected void populateRelyingPartyData(ShibbolethSSORequestContext requestContext) throws ProfileException {
303 requestContext.setRelyingPartyMetadata(getMetadataProvider().getEntityDescriptor(
304 requestContext.getRelyingPartyId()));
306 RoleDescriptor relyingPartyRole = requestContext.getRelyingPartyMetadata().getSPSSODescriptor(
307 SAMLConstants.SAML11P_NS);
309 if (relyingPartyRole == null) {
310 relyingPartyRole = requestContext.getRelyingPartyMetadata()
311 .getSPSSODescriptor(SAMLConstants.SAML10P_NS);
312 if (relyingPartyRole == null) {
313 throw new MetadataProviderException("Unable to locate SPSSO role descriptor for entity "
314 + requestContext.getRelyingPartyId());
317 requestContext.setRelyingPartyRoleMetadata(relyingPartyRole);
319 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(requestContext.getRelyingPartyId());
320 requestContext.setRelyingPartyConfiguration(rpConfig);
322 requestContext.setProfileConfiguration((ShibbolethSSOConfiguration) rpConfig
323 .getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID));
325 } catch (MetadataProviderException e) {
326 log.error("Unable to locate metadata for relying party " + requestContext.getRelyingPartyId());
327 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
328 "Unable to locate metadata for relying party " + requestContext.getRelyingPartyId()));
329 throw new ProfileException("Unable to locate metadata for relying party "
330 + requestContext.getRelyingPartyId());
335 * Populates the asserting party entity and role metadata.
337 * @param requestContext current request context with relying party configuration populated
339 * @throws ProfileException thrown if metadata can not be located for the asserting party
341 protected void populateAssertingPartyData(ShibbolethSSORequestContext requestContext) throws ProfileException {
342 String assertingPartyId = requestContext.getRelyingPartyConfiguration().getProviderId();
345 requestContext.setAssertingPartyId(assertingPartyId);
347 requestContext.setAssertingPartyMetadata(getMetadataProvider().getEntityDescriptor(assertingPartyId));
349 RoleDescriptor assertingPartyRole = requestContext.getAssertingPartyMetadata().getIDPSSODescriptor(
350 ShibbolethConstants.SHIB_SSO_PROFILE_URI);
351 if (assertingPartyRole == null) {
352 throw new MetadataProviderException("Unable to locate IDPSSO role descriptor for entity "
355 requestContext.setAssertingPartyRoleMetadata(assertingPartyRole);
356 } catch (MetadataProviderException e) {
357 log.error("Unable to locate metadata for asserting party " + assertingPartyId);
358 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
359 "Unable to locate metadata for relying party " + assertingPartyId));
360 throw new ProfileException("Unable to locate metadata for relying party " + assertingPartyId);
365 * Builds the authentication statement for the authenticated principal.
367 * @param requestContext current request context
369 * @return the created statement
371 * @throws ProfileException thrown if the authentication statement can not be created
373 protected AuthenticationStatement buildAuthenticationStatement(ShibbolethSSORequestContext requestContext)
374 throws ProfileException {
375 ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
377 AuthenticationStatement statement = getAuthenticationStatementBuilder().buildObject();
378 statement.setAuthenticationInstant(loginContext.getAuthenticationInstant());
379 statement.setAuthenticationMethod(loginContext.getAuthenticationMethod());
382 statement.setSubjectLocality(null);
384 Subject statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches");
385 statement.setSubject(statementSubject);
391 * Encodes the request's SAML response and writes it to the servlet response.
393 * @param requestContext current request context
395 * @throws ProfileException thrown if no message encoder is registered for this profiles binding
397 protected void encodeResponse(ShibbolethSSORequestContext requestContext) throws ProfileException {
398 if (log.isDebugEnabled()) {
399 log.debug("Encoding response to SAML request from relying party " + requestContext.getRelyingPartyId());
402 BasicEndpointSelector endpointSelector = new BasicEndpointSelector();
403 endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
404 endpointSelector.setMetadataProvider(getMetadataProvider());
405 endpointSelector.setRelyingParty(requestContext.getRelyingPartyMetadata());
406 endpointSelector.setRelyingPartyRole(requestContext.getRelyingPartyRoleMetadata());
407 endpointSelector.setSamlRequest(requestContext.getSamlRequest());
408 endpointSelector.getSupportedIssuerBindings().addAll(getMessageEncoderFactory().getEncoderBuilders().keySet());
409 Endpoint relyingPartyEndpoint = endpointSelector.selectEndpoint();
411 if (relyingPartyEndpoint == null) {
412 log.error("Unable to determine endpoint, from metadata, for relying party "
413 + requestContext.getRelyingPartyId() + " acting in SPSSO role");
414 throw new ProfileException("Unable to determine endpoint, from metadata, for relying party "
415 + requestContext.getRelyingPartyId() + " acting in SPSSO role");
418 MessageEncoder<ServletResponse> encoder = getMessageEncoderFactory().getMessageEncoder(
419 relyingPartyEndpoint.getBinding());
421 super.populateMessageEncoder(encoder);
422 ProfileResponse<ServletResponse> profileResponse = requestContext.getProfileResponse();
423 encoder.setResponse(profileResponse.getRawResponse());
424 encoder.setSamlMessage(requestContext.getSamlResponse());
425 requestContext.setMessageEncoder(encoder);
429 } catch (BindingException e) {
430 throw new ProfileException("Unable to encode response to relying party: "
431 + requestContext.getRelyingPartyId(), e);
435 /** Represents the internal state of a Shibboleth SSO Request while it's being processed by the IdP. */
436 protected class ShibbolethSSORequestContext extends
437 SAML1ProfileRequestContext<SAMLObject, Response, ShibbolethSSOConfiguration> {
439 /** Current login context. */
440 private ShibbolethSSOLoginContext loginContext;
445 * @param request current profile request
446 * @param response current profile response
448 public ShibbolethSSORequestContext(ProfileRequest<ServletRequest> request,
449 ProfileResponse<ServletResponse> response) {
450 super(request, response);
454 * Gets the current login context.
456 * @return current login context
458 public ShibbolethSSOLoginContext getLoginContext() {
463 * Sets the current login context.
465 * @param context current login context
467 public void setLoginContext(ShibbolethSSOLoginContext context) {
468 loginContext = context;