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
70 * @param encoder URI of the encoding binding
72 * @throws IllegalArgumentException thrown if either the authentication manager path or encoding binding URI are
75 public ShibbolethSSOProfileHandler(String authnManagerPath) {
76 if (DatatypeHelper.isEmpty(authnManagerPath)) {
77 throw new IllegalArgumentException("Authentication manager path may not be null");
80 authenticationManagerPath = authnManagerPath;
82 authnStatementBuilder = (SAMLObjectBuilder<AuthenticationStatement>) getBuilderFactory().getBuilder(
83 AuthenticationStatement.DEFAULT_ELEMENT_NAME);
87 * Convenience method for getting the SAML 1 AuthenticationStatement builder.
89 * @return SAML 1 AuthenticationStatement builder
91 public SAMLObjectBuilder<AuthenticationStatement> getAuthenticationStatementBuilder() {
92 return authnStatementBuilder;
96 public String getProfileId() {
97 return "urn:mace:shibboleth:2.0:idp:profiles:shibboleth:request:sso";
101 public void processRequest(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response)
102 throws ProfileException {
104 HttpSession httpSession = ((HttpServletRequest) request.getRawRequest()).getSession(true);
105 if (httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY) == null) {
106 performAuthentication(request, response);
108 completeAuthenticationRequest(request, response);
113 * Creates a {@link LoginContext} an sends the request off to the AuthenticationManager to begin the process of
114 * authenticating the user.
116 * @param request current request
117 * @param response current response
119 * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
120 * authentication manager
122 protected void performAuthentication(ProfileRequest<ServletRequest> request,
123 ProfileResponse<ServletResponse> response) throws ProfileException {
125 HttpServletRequest httpRequest = (HttpServletRequest) request.getRawRequest();
126 HttpServletResponse httpResponse = (HttpServletResponse) response.getRawResponse();
127 HttpSession httpSession = httpRequest.getSession(true);
129 LoginContext loginContext = buildLoginContext(httpRequest);
130 httpSession.setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
133 RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
134 dispatcher.forward(httpRequest, httpResponse);
135 } catch (IOException ex) {
136 log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
137 throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
138 } catch (ServletException ex) {
139 log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
140 throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
145 * Creates a response to the Shibboleth SSO and sends the user, with response in tow, back to the relying party
146 * after they've been authenticated.
148 * @param request current request
149 * @param response current response
151 * @throws ProfileException thrown if the response can not be created and sent back to the relying party
153 protected void completeAuthenticationRequest(ProfileRequest<ServletRequest> request,
154 ProfileResponse<ServletResponse> response) throws ProfileException {
155 HttpSession httpSession = ((HttpServletRequest) request.getRawRequest()).getSession(true);
157 ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) httpSession
158 .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
159 httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
161 ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, request, response);
163 Response samlResponse;
165 if (!loginContext.isPrincipalAuthenticated()) {
166 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "User failed authentication"));
167 throw new ProfileException("User failed authentication");
170 ArrayList<Statement> statements = new ArrayList<Statement>();
171 statements.add(buildAuthenticationStatement(requestContext));
172 if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
174 .add(buildAttributeStatement(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches"));
177 samlResponse = buildResponse(requestContext, statements);
178 } catch (ProfileException e) {
179 samlResponse = buildErrorResponse(requestContext);
182 requestContext.setSamlResponse(samlResponse);
183 encodeResponse(requestContext);
184 writeAuditLogEntry(requestContext);
188 * Creates a login context from the incoming HTTP request.
190 * @param request current HTTP request
192 * @return the constructed login context
194 * @throws ProfileException thrown if the incomming request did not contain a providerId, shire, and target
197 protected ShibbolethSSOLoginContext buildLoginContext(HttpServletRequest request) throws ProfileException {
198 ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
201 String providerId = DatatypeHelper.safeTrimOrNullString(request.getParameter("providerId"));
202 if (providerId == null) {
203 log.error("No providerId parameter in Shibboleth SSO request");
204 throw new ProfileException("No providerId parameter in Shibboleth SSO request");
206 loginContext.setRelyingParty(URLDecoder.decode(providerId, "UTF-8"));
208 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(providerId);
209 if(rpConfig == null){
210 log.error("No relying party configuration available for " + providerId);
211 throw new ProfileException("No relying party configuration available for " + providerId);
213 loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
215 String acs = DatatypeHelper.safeTrimOrNullString(request.getParameter("shire"));
217 log.error("No shire parameter in Shibboleth SSO request");
218 throw new ProfileException("No shire parameter in Shibboleth SSO request");
220 loginContext.setSpAssertionConsumerService(URLDecoder.decode(acs, "UTF-8"));
222 String target = DatatypeHelper.safeTrimOrNullString(request.getParameter("target"));
223 if (target == null) {
224 log.error("No target parameter in Shibboleth SSO request");
225 throw new ProfileException("No target parameter in Shibboleth SSO request");
227 loginContext.setSpTarget(URLDecoder.decode(target, "UTF-8"));
228 } catch (UnsupportedEncodingException e) {
229 // UTF-8 encoding required to be supported by all JVMs.
232 loginContext.setAuthenticationEngineURL(authenticationManagerPath);
233 loginContext.setProfileHandlerURL(request.getRequestURI());
238 * Creates an authentication request context from the current environmental information.
240 * @param loginContext current login context
241 * @param request current request
242 * @param response current response
244 * @return created authentication request context
246 * @throws ProfileException thrown if asserting and relying party metadata can not be located
248 protected ShibbolethSSORequestContext buildRequestContext(ShibbolethSSOLoginContext loginContext,
249 ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response) throws ProfileException {
250 ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext(request, response);
252 requestContext.setLoginContext(loginContext);
254 requestContext.setPrincipalName(loginContext.getPrincipalName());
256 requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
258 String relyingPartyId = loginContext.getRelyingPartyId();
260 requestContext.setRelyingPartyId(relyingPartyId);
264 requestContext.setRelyingPartyMetadata(getMetadataProvider().getEntityDescriptor(
265 requestContext.getRelyingPartyId()));
267 requestContext.setRelyingPartyRoleMetadata(requestContext.getRelyingPartyMetadata().getSPSSODescriptor(
268 SAMLConstants.SAML1P_NS));
270 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
271 requestContext.setRelyingPartyConfiguration(rpConfig);
273 requestContext.setAssertingPartyId(requestContext.getRelyingPartyConfiguration().getProviderId());
275 requestContext.setAssertingPartyMetadata(getMetadataProvider().getEntityDescriptor(
276 requestContext.getAssertingPartyId()));
278 requestContext.setAssertingPartyRoleMetadata(requestContext.getAssertingPartyMetadata()
279 .getIDPSSODescriptor(SAMLConstants.SAML1P_NS));
281 requestContext.setProfileConfiguration((ShibbolethSSOConfiguration) rpConfig
282 .getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID));
284 return requestContext;
285 } catch (MetadataProviderException e) {
286 log.error("Unable to locate metadata for asserting or relying party");
287 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error locating party metadata"));
288 throw new ProfileException("Error locating party metadata");
293 * Builds the authentication statement for the authenticated principal.
295 * @param requestContext current request context
297 * @return the created statement
299 * @throws ProfileException thrown if the authentication statement can not be created
301 protected AuthenticationStatement buildAuthenticationStatement(ShibbolethSSORequestContext requestContext)
302 throws ProfileException {
303 ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
305 AuthenticationStatement statement = getAuthenticationStatementBuilder().buildObject();
306 statement.setAuthenticationInstant(loginContext.getAuthenticationInstant());
307 statement.setAuthenticationMethod(loginContext.getAuthenticationMethod());
310 statement.setSubjectLocality(null);
312 Subject statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches");
313 statement.setSubject(statementSubject);
319 * Encodes the request's SAML response and writes it to the servlet response.
321 * @param requestContext current request context
323 * @throws ProfileException thrown if no message encoder is registered for this profiles binding
325 protected void encodeResponse(ShibbolethSSORequestContext requestContext) throws ProfileException {
326 if (log.isDebugEnabled()) {
327 log.debug("Encoding response to SAML request from relying party " + requestContext.getRelyingPartyId());
331 //TODO endpoint selection
332 MessageEncoder<ServletResponse> encoder = null;
334 super.populateMessageEncoder(encoder);
335 ProfileResponse<ServletResponse> profileResponse = requestContext.getProfileResponse();
336 encoder.setResponse(profileResponse.getRawResponse());
337 encoder.setSamlMessage(requestContext.getSamlResponse());
338 requestContext.setMessageEncoder(encoder);
342 } catch (BindingException e) {
343 throw new ProfileException("Unable to encode response to relying party: "
344 + requestContext.getRelyingPartyId(), e);
348 /** Represents the internal state of a Shibboleth SSO Request while it's being processed by the IdP. */
349 protected class ShibbolethSSORequestContext extends
350 SAML1ProfileRequestContext<SAMLObject, Response, ShibbolethSSOConfiguration> {
352 /** Current login context. */
353 private ShibbolethSSOLoginContext loginContext;
358 * @param request current profile request
359 * @param response current profile response
361 public ShibbolethSSORequestContext(ProfileRequest<ServletRequest> request,
362 ProfileResponse<ServletResponse> response) {
363 super(request, response);
367 * Gets the current login context.
369 * @return current login context
371 public ShibbolethSSOLoginContext getLoginContext() {
376 * Sets the current login context.
378 * @param context current login context
380 public void setLoginContext(ShibbolethSSOLoginContext context) {
381 loginContext = context;