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.BindingException;
36 import org.opensaml.common.binding.encoding.MessageEncoder;
37 import org.opensaml.common.xml.SAMLConstants;
38 import org.opensaml.saml1.core.AuthenticationStatement;
39 import org.opensaml.saml1.core.Response;
40 import org.opensaml.saml1.core.Statement;
41 import org.opensaml.saml1.core.StatusCode;
42 import org.opensaml.saml1.core.Subject;
43 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
44 import org.opensaml.xml.util.DatatypeHelper;
46 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
47 import edu.internet2.middleware.shibboleth.common.profile.ProfileRequest;
48 import edu.internet2.middleware.shibboleth.common.profile.ProfileResponse;
49 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
50 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml1.ShibbolethSSOConfiguration;
51 import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
52 import edu.internet2.middleware.shibboleth.idp.authn.ShibbolethSSOLoginContext;
54 /** Shibboleth SSO request profile handler. */
55 public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
58 private final Logger log = Logger.getLogger(ShibbolethSSOProfileHandler.class);
60 /** Builder of AuthenticationStatement objects. */
61 private SAMLObjectBuilder<AuthenticationStatement> authnStatementBuilder;
63 /** URL of the authentication manager servlet. */
64 private String authenticationManagerPath;
69 * @param authnManagerPath path to the authentication manager servlet
71 * @throws IllegalArgumentException thrown if either the authentication manager path or encoding binding URI are
74 public ShibbolethSSOProfileHandler(String authnManagerPath) {
75 if (DatatypeHelper.isEmpty(authnManagerPath)) {
76 throw new IllegalArgumentException("Authentication manager path may not be null");
79 authenticationManagerPath = authnManagerPath;
81 authnStatementBuilder = (SAMLObjectBuilder<AuthenticationStatement>) getBuilderFactory().getBuilder(
82 AuthenticationStatement.DEFAULT_ELEMENT_NAME);
86 * Convenience method for getting the SAML 1 AuthenticationStatement builder.
88 * @return SAML 1 AuthenticationStatement builder
90 public SAMLObjectBuilder<AuthenticationStatement> getAuthenticationStatementBuilder() {
91 return authnStatementBuilder;
95 public String getProfileId() {
96 return "urn:mace:shibboleth:2.0:idp:profiles:shibboleth:request:sso";
100 public void processRequest(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response)
101 throws ProfileException {
103 HttpSession httpSession = ((HttpServletRequest) request.getRawRequest()).getSession(true);
104 if (httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY) == null) {
105 performAuthentication(request, response);
107 completeAuthenticationRequest(request, response);
112 * Creates a {@link LoginContext} an sends the request off to the AuthenticationManager to begin the process of
113 * authenticating the user.
115 * @param request current request
116 * @param response current response
118 * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
119 * authentication manager
121 protected void performAuthentication(ProfileRequest<ServletRequest> request,
122 ProfileResponse<ServletResponse> response) throws ProfileException {
124 HttpServletRequest httpRequest = (HttpServletRequest) request.getRawRequest();
125 HttpServletResponse httpResponse = (HttpServletResponse) response.getRawResponse();
126 HttpSession httpSession = httpRequest.getSession(true);
128 LoginContext loginContext = buildLoginContext(httpRequest);
129 httpSession.setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
132 RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
133 dispatcher.forward(httpRequest, httpResponse);
134 } catch (IOException ex) {
135 log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
136 throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
137 } catch (ServletException ex) {
138 log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
139 throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
144 * Creates a response to the Shibboleth SSO and sends the user, with response in tow, back to the relying party
145 * after they've been authenticated.
147 * @param request current request
148 * @param response current response
150 * @throws ProfileException thrown if the response can not be created and sent back to the relying party
152 protected void completeAuthenticationRequest(ProfileRequest<ServletRequest> request,
153 ProfileResponse<ServletResponse> response) throws ProfileException {
154 HttpSession httpSession = ((HttpServletRequest) request.getRawRequest()).getSession(true);
156 ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) httpSession
157 .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
158 httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
160 ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, request, response);
162 Response samlResponse;
164 if (!loginContext.isPrincipalAuthenticated()) {
165 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "User failed authentication"));
166 throw new ProfileException("User failed authentication");
169 ArrayList<Statement> statements = new ArrayList<Statement>();
170 statements.add(buildAuthenticationStatement(requestContext));
171 if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
173 .add(buildAttributeStatement(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches"));
176 samlResponse = buildResponse(requestContext, statements);
177 } catch (ProfileException e) {
178 samlResponse = buildErrorResponse(requestContext);
181 requestContext.setSamlResponse(samlResponse);
182 encodeResponse(requestContext);
183 writeAuditLogEntry(requestContext);
187 * Creates a login context from the incoming HTTP request.
189 * @param request current HTTP request
191 * @return the constructed login context
193 * @throws ProfileException thrown if the incomming request did not contain a providerId, shire, and target
196 protected ShibbolethSSOLoginContext buildLoginContext(HttpServletRequest request) throws ProfileException {
197 ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
200 String providerId = DatatypeHelper.safeTrimOrNullString(request.getParameter("providerId"));
201 if (providerId == null) {
202 log.error("No providerId parameter in Shibboleth SSO request");
203 throw new ProfileException("No providerId parameter in Shibboleth SSO request");
205 loginContext.setRelyingParty(URLDecoder.decode(providerId, "UTF-8"));
207 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(providerId);
208 if(rpConfig == null){
209 log.error("No relying party configuration available for " + providerId);
210 throw new ProfileException("No relying party configuration available for " + providerId);
212 loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
214 String acs = DatatypeHelper.safeTrimOrNullString(request.getParameter("shire"));
216 log.error("No shire parameter in Shibboleth SSO request");
217 throw new ProfileException("No shire parameter in Shibboleth SSO request");
219 loginContext.setSpAssertionConsumerService(URLDecoder.decode(acs, "UTF-8"));
221 String target = DatatypeHelper.safeTrimOrNullString(request.getParameter("target"));
222 if (target == null) {
223 log.error("No target parameter in Shibboleth SSO request");
224 throw new ProfileException("No target parameter in Shibboleth SSO request");
226 loginContext.setSpTarget(URLDecoder.decode(target, "UTF-8"));
227 } catch (UnsupportedEncodingException e) {
228 // UTF-8 encoding required to be supported by all JVMs.
231 loginContext.setAuthenticationEngineURL(authenticationManagerPath);
232 loginContext.setProfileHandlerURL(request.getRequestURI());
237 * Creates an authentication request context from the current environmental information.
239 * @param loginContext current login context
240 * @param request current request
241 * @param response current response
243 * @return created authentication request context
245 * @throws ProfileException thrown if asserting and relying party metadata can not be located
247 protected ShibbolethSSORequestContext buildRequestContext(ShibbolethSSOLoginContext loginContext,
248 ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response) throws ProfileException {
249 ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext(request, response);
251 requestContext.setLoginContext(loginContext);
253 requestContext.setPrincipalName(loginContext.getPrincipalName());
255 requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
257 String relyingPartyId = loginContext.getRelyingPartyId();
259 requestContext.setRelyingPartyId(relyingPartyId);
263 requestContext.setRelyingPartyMetadata(getMetadataProvider().getEntityDescriptor(
264 requestContext.getRelyingPartyId()));
266 requestContext.setRelyingPartyRoleMetadata(requestContext.getRelyingPartyMetadata().getSPSSODescriptor(
267 SAMLConstants.SAML1P_NS));
269 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
270 requestContext.setRelyingPartyConfiguration(rpConfig);
272 requestContext.setAssertingPartyId(requestContext.getRelyingPartyConfiguration().getProviderId());
274 requestContext.setAssertingPartyMetadata(getMetadataProvider().getEntityDescriptor(
275 requestContext.getAssertingPartyId()));
277 requestContext.setAssertingPartyRoleMetadata(requestContext.getAssertingPartyMetadata()
278 .getIDPSSODescriptor(SAMLConstants.SAML1P_NS));
280 requestContext.setProfileConfiguration((ShibbolethSSOConfiguration) rpConfig
281 .getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID));
283 return requestContext;
284 } catch (MetadataProviderException e) {
285 log.error("Unable to locate metadata for asserting or relying party");
286 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error locating party metadata"));
287 throw new ProfileException("Error locating party metadata");
292 * Builds the authentication statement for the authenticated principal.
294 * @param requestContext current request context
296 * @return the created statement
298 * @throws ProfileException thrown if the authentication statement can not be created
300 protected AuthenticationStatement buildAuthenticationStatement(ShibbolethSSORequestContext requestContext)
301 throws ProfileException {
302 ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
304 AuthenticationStatement statement = getAuthenticationStatementBuilder().buildObject();
305 statement.setAuthenticationInstant(loginContext.getAuthenticationInstant());
306 statement.setAuthenticationMethod(loginContext.getAuthenticationMethod());
309 statement.setSubjectLocality(null);
311 Subject statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches");
312 statement.setSubject(statementSubject);
318 * Encodes the request's SAML response and writes it to the servlet response.
320 * @param requestContext current request context
322 * @throws ProfileException thrown if no message encoder is registered for this profiles binding
324 protected void encodeResponse(ShibbolethSSORequestContext requestContext) throws ProfileException {
325 if (log.isDebugEnabled()) {
326 log.debug("Encoding response to SAML request from relying party " + requestContext.getRelyingPartyId());
330 //TODO endpoint selection
331 MessageEncoder<ServletResponse> encoder = null;
333 super.populateMessageEncoder(encoder);
334 ProfileResponse<ServletResponse> profileResponse = requestContext.getProfileResponse();
335 encoder.setResponse(profileResponse.getRawResponse());
336 encoder.setSamlMessage(requestContext.getSamlResponse());
337 requestContext.setMessageEncoder(encoder);
341 } catch (BindingException e) {
342 throw new ProfileException("Unable to encode response to relying party: "
343 + requestContext.getRelyingPartyId(), e);
347 /** Represents the internal state of a Shibboleth SSO Request while it's being processed by the IdP. */
348 protected class ShibbolethSSORequestContext extends
349 SAML1ProfileRequestContext<SAMLObject, Response, ShibbolethSSOConfiguration> {
351 /** Current login context. */
352 private ShibbolethSSOLoginContext loginContext;
357 * @param request current profile request
358 * @param response current profile response
360 public ShibbolethSSORequestContext(ProfileRequest<ServletRequest> request,
361 ProfileResponse<ServletResponse> response) {
362 super(request, response);
366 * Gets the current login context.
368 * @return current login context
370 public ShibbolethSSOLoginContext getLoginContext() {
375 * Sets the current login context.
377 * @param context current login context
379 public void setLoginContext(ShibbolethSSOLoginContext context) {
380 loginContext = context;