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.provider.MetadataProviderException;
47 import org.opensaml.xml.util.DatatypeHelper;
49 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
50 import edu.internet2.middleware.shibboleth.common.profile.ProfileRequest;
51 import edu.internet2.middleware.shibboleth.common.profile.ProfileResponse;
52 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
53 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml1.ShibbolethSSOConfiguration;
54 import edu.internet2.middleware.shibboleth.common.util.HttpHelper;
55 import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
56 import edu.internet2.middleware.shibboleth.idp.authn.ShibbolethSSOLoginContext;
58 /** Shibboleth SSO request profile handler. */
59 public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
62 private final Logger log = Logger.getLogger(ShibbolethSSOProfileHandler.class);
64 /** Builder of AuthenticationStatement objects. */
65 private SAMLObjectBuilder<AuthenticationStatement> authnStatementBuilder;
67 /** URL of the authentication manager servlet. */
68 private String authenticationManagerPath;
73 * @param authnManagerPath path to the authentication manager servlet
75 * @throws IllegalArgumentException thrown if either the authentication manager path or encoding binding URI are
78 public ShibbolethSSOProfileHandler(String authnManagerPath) {
79 if (DatatypeHelper.isEmpty(authnManagerPath)) {
80 throw new IllegalArgumentException("Authentication manager path may not be null");
83 authenticationManagerPath = authnManagerPath;
85 authnStatementBuilder = (SAMLObjectBuilder<AuthenticationStatement>) getBuilderFactory().getBuilder(
86 AuthenticationStatement.DEFAULT_ELEMENT_NAME);
90 * Convenience method for getting the SAML 1 AuthenticationStatement builder.
92 * @return SAML 1 AuthenticationStatement builder
94 public SAMLObjectBuilder<AuthenticationStatement> getAuthenticationStatementBuilder() {
95 return authnStatementBuilder;
99 public String getProfileId() {
100 return "urn:mace:shibboleth:2.0:idp:profiles:shibboleth:request:sso";
104 public void processRequest(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response)
105 throws ProfileException {
107 if (response.getRawResponse().isCommitted()) {
108 log.error("HTTP Response already committed");
111 if (log.isDebugEnabled()) {
112 log.debug("Processing incomming request");
114 HttpSession httpSession = ((HttpServletRequest) request.getRawRequest()).getSession(true);
115 if (httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY) == null) {
116 if (log.isDebugEnabled()) {
117 log.debug("User session does not contain a login context, processing as first leg of request");
119 performAuthentication(request, response);
121 if (log.isDebugEnabled()) {
122 log.debug("User session contains a login context, processing as second leg of request");
124 completeAuthenticationRequest(request, response);
129 * Creates a {@link LoginContext} an sends the request off to the AuthenticationManager to begin the process of
130 * authenticating the user.
132 * @param request current request
133 * @param response current response
135 * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
136 * authentication manager
138 protected void performAuthentication(ProfileRequest<ServletRequest> request,
139 ProfileResponse<ServletResponse> response) throws ProfileException {
141 HttpServletRequest httpRequest = (HttpServletRequest) request.getRawRequest();
142 HttpServletResponse httpResponse = (HttpServletResponse) response.getRawResponse();
143 HttpSession httpSession = httpRequest.getSession(true);
145 LoginContext loginContext = buildLoginContext(httpRequest);
146 if (getRelyingPartyConfiguration(loginContext.getRelyingPartyId()) == null) {
147 log.error("Shibboleth SSO profile is not configured for relying party "
148 + loginContext.getRelyingPartyId());
149 throw new ProfileException("Shibboleth SSO profile is not configured for relying party "
150 + loginContext.getRelyingPartyId());
153 httpSession.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 * Creates a response to the Shibboleth SSO and sends the user, with response in tow, back to the relying party
170 * after they've been authenticated.
172 * @param request current request
173 * @param response current response
175 * @throws ProfileException thrown if the response can not be created and sent back to the relying party
177 protected void completeAuthenticationRequest(ProfileRequest<ServletRequest> request,
178 ProfileResponse<ServletResponse> response) throws ProfileException {
179 HttpSession httpSession = ((HttpServletRequest) request.getRawRequest()).getSession(true);
181 ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) httpSession
182 .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
183 httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
185 ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, request, response);
187 Response samlResponse;
189 if (!loginContext.isPrincipalAuthenticated()) {
190 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "User failed authentication"));
191 throw new ProfileException("User failed authentication");
194 ArrayList<Statement> statements = new ArrayList<Statement>();
195 statements.add(buildAuthenticationStatement(requestContext));
196 if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
198 .add(buildAttributeStatement(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches"));
201 samlResponse = buildResponse(requestContext, statements);
202 } catch (ProfileException e) {
203 samlResponse = buildErrorResponse(requestContext);
206 requestContext.setSamlResponse(samlResponse);
207 encodeResponse(requestContext);
208 writeAuditLogEntry(requestContext);
212 * Creates a login context from the incoming HTTP request.
214 * @param request current HTTP request
216 * @return the constructed login context
218 * @throws ProfileException thrown if the incomming request did not contain a providerId, shire, and target
221 protected ShibbolethSSOLoginContext buildLoginContext(HttpServletRequest request) throws ProfileException {
222 ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
225 String providerId = DatatypeHelper.safeTrimOrNullString(request.getParameter("providerId"));
226 if (providerId == null) {
227 log.error("No providerId parameter in Shibboleth SSO request");
228 throw new ProfileException("No providerId parameter in Shibboleth SSO request");
230 loginContext.setRelyingParty(URLDecoder.decode(providerId, "UTF-8"));
232 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(providerId);
233 if (rpConfig == null) {
234 log.error("No relying party configuration available for " + providerId);
235 throw new ProfileException("No relying party configuration available for " + providerId);
237 loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
239 String acs = DatatypeHelper.safeTrimOrNullString(request.getParameter("shire"));
241 log.error("No shire parameter in Shibboleth SSO request");
242 throw new ProfileException("No shire parameter in Shibboleth SSO request");
244 loginContext.setSpAssertionConsumerService(URLDecoder.decode(acs, "UTF-8"));
246 String target = DatatypeHelper.safeTrimOrNullString(request.getParameter("target"));
247 if (target == null) {
248 log.error("No target parameter in Shibboleth SSO request");
249 throw new ProfileException("No target parameter in Shibboleth SSO request");
251 loginContext.setSpTarget(URLDecoder.decode(target, "UTF-8"));
252 } catch (UnsupportedEncodingException e) {
253 // UTF-8 encoding required to be supported by all JVMs.
256 loginContext.setAuthenticationEngineURL(authenticationManagerPath);
257 loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(request));
262 * Creates an authentication request context from the current environmental information.
264 * @param loginContext current login context
265 * @param request current request
266 * @param response current response
268 * @return created authentication request context
270 * @throws ProfileException thrown if asserting and relying party metadata can not be located
272 protected ShibbolethSSORequestContext buildRequestContext(ShibbolethSSOLoginContext loginContext,
273 ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response) throws ProfileException {
274 ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext(request, response);
276 requestContext.setLoginContext(loginContext);
278 requestContext.setPrincipalName(loginContext.getPrincipalName());
280 requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
282 String relyingPartyId = loginContext.getRelyingPartyId();
284 requestContext.setRelyingPartyId(relyingPartyId);
288 requestContext.setRelyingPartyMetadata(getMetadataProvider().getEntityDescriptor(
289 requestContext.getRelyingPartyId()));
291 requestContext.setRelyingPartyRoleMetadata(requestContext.getRelyingPartyMetadata().getSPSSODescriptor(
292 SAMLConstants.SAML1P_NS));
294 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
295 requestContext.setRelyingPartyConfiguration(rpConfig);
297 requestContext.setAssertingPartyId(requestContext.getRelyingPartyConfiguration().getProviderId());
299 requestContext.setAssertingPartyMetadata(getMetadataProvider().getEntityDescriptor(
300 requestContext.getAssertingPartyId()));
302 requestContext.setAssertingPartyRoleMetadata(requestContext.getAssertingPartyMetadata()
303 .getIDPSSODescriptor(SAMLConstants.SAML1P_NS));
305 requestContext.setProfileConfiguration((ShibbolethSSOConfiguration) rpConfig
306 .getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID));
308 return requestContext;
309 } catch (MetadataProviderException e) {
310 log.error("Unable to locate metadata for asserting or relying party");
311 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error locating party metadata"));
312 throw new ProfileException("Error locating party metadata");
317 * Builds the authentication statement for the authenticated principal.
319 * @param requestContext current request context
321 * @return the created statement
323 * @throws ProfileException thrown if the authentication statement can not be created
325 protected AuthenticationStatement buildAuthenticationStatement(ShibbolethSSORequestContext requestContext)
326 throws ProfileException {
327 ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
329 AuthenticationStatement statement = getAuthenticationStatementBuilder().buildObject();
330 statement.setAuthenticationInstant(loginContext.getAuthenticationInstant());
331 statement.setAuthenticationMethod(loginContext.getAuthenticationMethod());
334 statement.setSubjectLocality(null);
336 Subject statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches");
337 statement.setSubject(statementSubject);
343 * Encodes the request's SAML response and writes it to the servlet response.
345 * @param requestContext current request context
347 * @throws ProfileException thrown if no message encoder is registered for this profiles binding
349 protected void encodeResponse(ShibbolethSSORequestContext requestContext) throws ProfileException {
350 if (log.isDebugEnabled()) {
351 log.debug("Encoding response to SAML request from relying party " + requestContext.getRelyingPartyId());
354 BasicEndpointSelector endpointSelector = new BasicEndpointSelector();
355 endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
356 endpointSelector.setMetadataProvider(getMetadataProvider());
357 endpointSelector.setRelyingParty(requestContext.getRelyingPartyMetadata());
358 endpointSelector.setRelyingPartyRole(requestContext.getRelyingPartyRoleMetadata());
359 endpointSelector.setSamlRequest(requestContext.getSamlRequest());
360 endpointSelector.getSupportedIssuerBindings().addAll(getMessageEncoderFactory().getEncoderBuilders().keySet());
361 Endpoint relyingPartyEndpoint = endpointSelector.selectEndpoint();
363 if (relyingPartyEndpoint == null) {
364 log.error("Unable to determine endpoint, from metadata, for relying party "
365 + requestContext.getRelyingPartyId() + " acting in SPSSO role");
366 throw new ProfileException("Unable to determine endpoint, from metadata, for relying party "
367 + requestContext.getRelyingPartyId() + " acting in SPSSO role");
370 MessageEncoder<ServletResponse> encoder = getMessageEncoderFactory().getMessageEncoder(
371 relyingPartyEndpoint.getBinding());
373 super.populateMessageEncoder(encoder);
374 ProfileResponse<ServletResponse> profileResponse = requestContext.getProfileResponse();
375 encoder.setResponse(profileResponse.getRawResponse());
376 encoder.setSamlMessage(requestContext.getSamlResponse());
377 requestContext.setMessageEncoder(encoder);
381 } catch (BindingException e) {
382 throw new ProfileException("Unable to encode response to relying party: "
383 + requestContext.getRelyingPartyId(), e);
387 /** Represents the internal state of a Shibboleth SSO Request while it's being processed by the IdP. */
388 protected class ShibbolethSSORequestContext extends
389 SAML1ProfileRequestContext<SAMLObject, Response, ShibbolethSSOConfiguration> {
391 /** Current login context. */
392 private ShibbolethSSOLoginContext loginContext;
397 * @param request current profile request
398 * @param response current profile response
400 public ShibbolethSSORequestContext(ProfileRequest<ServletRequest> request,
401 ProfileResponse<ServletResponse> response) {
402 super(request, response);
406 * Gets the current login context.
408 * @return current login context
410 public ShibbolethSSOLoginContext getLoginContext() {
415 * Sets the current login context.
417 * @param context current login context
419 public void setLoginContext(ShibbolethSSOLoginContext context) {
420 loginContext = context;