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.saml1.core.AuthenticationStatement;
38 import org.opensaml.saml1.core.Response;
39 import org.opensaml.saml1.core.Statement;
40 import org.opensaml.saml1.core.StatusCode;
41 import org.opensaml.saml1.core.Subject;
42 import org.opensaml.saml2.metadata.IDPSSODescriptor;
43 import org.opensaml.saml2.metadata.SPSSODescriptor;
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;
66 /** Message encoder binding URI. */
67 private String encodingBinding;
72 * @param authnManagerPath path to the authentication manager servlet
73 * @param encoder URI of the encoding binding
75 * @throws IllegalArgumentException thrown if either the authentication manager path or encoding binding URI are
78 public ShibbolethSSOProfileHandler(String authnManagerPath, String encoder) {
79 if (DatatypeHelper.isEmpty(authnManagerPath) || DatatypeHelper.isEmpty(encoder)) {
80 throw new IllegalArgumentException("Authentication manager path and encoder binding URI may not be null");
83 authenticationManagerPath = authnManagerPath;
84 encodingBinding = encoder;
86 authnStatementBuilder = (SAMLObjectBuilder<AuthenticationStatement>) getBuilderFactory().getBuilder(
87 AuthenticationStatement.DEFAULT_ELEMENT_NAME);
91 * Convenience method for getting the SAML 1 AuthenticationStatement builder.
93 * @return SAML 1 AuthenticationStatement builder
95 public SAMLObjectBuilder<AuthenticationStatement> getAuthenticationStatementBuilder() {
96 return authnStatementBuilder;
100 public String getProfileId() {
101 return "urn:mace:shibboleth:2.0:idp:profiles:shibboleth:request:sso";
105 public void processRequest(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response)
106 throws ProfileException {
108 HttpSession httpSession = ((HttpServletRequest) request.getRawRequest()).getSession(true);
109 if (httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY) == null) {
110 performAuthentication(request, response);
112 completeAuthenticationRequest(request, response);
117 * Creates a {@link LoginContext} an sends the request off to the AuthenticationManager to begin the process of
118 * authenticating the user.
120 * @param request current request
121 * @param response current response
123 * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
124 * authentication manager
126 protected void performAuthentication(ProfileRequest<ServletRequest> request,
127 ProfileResponse<ServletResponse> response) throws ProfileException {
129 HttpServletRequest httpRequest = (HttpServletRequest) request.getRawRequest();
130 HttpServletResponse httpResponse = (HttpServletResponse) response.getRawResponse();
131 HttpSession httpSession = httpRequest.getSession(true);
133 LoginContext loginContext = buildLoginContext(httpRequest);
134 httpSession.setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
137 RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
138 dispatcher.forward(httpRequest, httpResponse);
139 } catch (IOException ex) {
140 log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
141 throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
142 } catch (ServletException ex) {
143 log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
144 throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
149 * Creates a response to the Shibboleth SSO and sends the user, with response in tow, back to the relying party
150 * after they've been authenticated.
152 * @param request current request
153 * @param response current response
155 * @throws ProfileException thrown if the response can not be created and sent back to the relying party
157 protected void completeAuthenticationRequest(ProfileRequest<ServletRequest> request,
158 ProfileResponse<ServletResponse> response) throws ProfileException {
159 HttpSession httpSession = ((HttpServletRequest) request.getRawRequest()).getSession(true);
161 ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) httpSession
162 .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
163 httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
165 ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, request, response);
167 Response samlResponse;
169 if (!loginContext.getAuthenticationOK()) {
170 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "User failed authentication"));
171 throw new ProfileException("User failed authentication");
174 ArrayList<Statement> statements = new ArrayList<Statement>();
175 statements.add(buildAuthenticationStatement(requestContext));
176 statements.add(buildAttributeStatement(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches"));
178 samlResponse = buildResponse(requestContext, statements);
179 } catch (ProfileException e) {
180 samlResponse = buildErrorResponse(requestContext);
183 requestContext.setSamlResponse(samlResponse);
184 encodeResponse(requestContext);
185 writeAuditLogEntry(requestContext);
189 * Creates a login context from the incoming HTTP request.
191 * @param request current HTTP request
193 * @return the constructed login context
195 * @throws ProfileException thrown if the incomming request did not contain a providerId, shire, and target
198 protected ShibbolethSSOLoginContext buildLoginContext(HttpServletRequest request) throws ProfileException {
199 ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
202 String providerId = DatatypeHelper.safeTrimOrNullString(request.getParameter("providerId"));
203 if (providerId == null) {
204 log.error("No providerId parameter in Shibboleth SSO request");
205 throw new ProfileException("No providerId parameter in Shibboleth SSO request");
207 loginContext.setRelyingParty(URLDecoder.decode(providerId, "UTF-8"));
209 String acs = DatatypeHelper.safeTrimOrNullString(request.getParameter("shire"));
211 log.error("No shire parameter in Shibboleth SSO request");
212 throw new ProfileException("No shire parameter in Shibboleth SSO request");
214 loginContext.setSpAssertionConsumerService(URLDecoder.decode(acs, "UTF-8"));
216 String target = DatatypeHelper.safeTrimOrNullString(request.getParameter("target"));
217 if (target == null) {
218 log.error("No target parameter in Shibboleth SSO request");
219 throw new ProfileException("No target parameter in Shibboleth SSO request");
221 loginContext.setSpTarget(URLDecoder.decode(target, "UTF-8"));
222 } catch (UnsupportedEncodingException e) {
223 // UTF-8 encoding required to be supported by all JVMs.
226 loginContext.setAuthenticationManagerURL(authenticationManagerPath);
227 loginContext.setProfileHandlerURL(request.getRequestURI());
232 * Creates an authentication request context from the current environmental information.
234 * @param loginContext current login context
235 * @param request current request
236 * @param response current response
238 * @return created authentication request context
240 protected ShibbolethSSORequestContext buildRequestContext(ShibbolethSSOLoginContext loginContext,
241 ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response) {
242 ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext(request, response);
244 requestContext.setLoginContext(loginContext);
246 requestContext.setPrincipalName(loginContext.getUserID());
248 requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
250 String relyingPartyId = loginContext.getRelyingPartyId();
252 requestContext.setRelyingPartyId(relyingPartyId);
254 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
255 requestContext.setRelyingPartyConfiguration(rpConfig);
257 requestContext.setRelyingPartyRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
259 requestContext.setAssertingPartyId(requestContext.getRelyingPartyConfiguration().getProviderId());
261 requestContext.setAssertingPartyRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
263 requestContext.setProfileConfiguration((ShibbolethSSOConfiguration) rpConfig
264 .getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID));
266 return requestContext;
270 * Builds the authentication statement for the authenticated principal.
272 * @param requestContext current request context
274 * @return the created statement
276 protected AuthenticationStatement buildAuthenticationStatement(ShibbolethSSORequestContext requestContext)
277 throws ProfileException {
278 ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
280 AuthenticationStatement statement = getAuthenticationStatementBuilder().buildObject();
281 statement.setAuthenticationInstant(loginContext.getAuthenticationInstant());
282 statement.setAuthenticationMethod(loginContext.getAuthenticationMethod());
285 statement.setSubjectLocality(null);
287 Subject statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches");
288 statement.setSubject(statementSubject);
294 * Encodes the request's SAML response and writes it to the servlet response.
296 * @param requestContext current request context
298 * @throws ProfileException thrown if no message encoder is registered for this profiles binding
300 protected void encodeResponse(ShibbolethSSORequestContext requestContext) throws ProfileException {
301 if (log.isDebugEnabled()) {
302 log.debug("Encoding response to SAML request from relying party " + requestContext.getRelyingPartyId());
304 MessageEncoder<ServletResponse> encoder = getMessageEncoderFactory().getMessageEncoder(encodingBinding);
305 if (encoder == null) {
306 throw new ProfileException("No response encoder was registered for binding type: " + encodingBinding);
309 super.populateMessageEncoder(encoder);
310 encoder.setResponse(requestContext.getProfileResponse().getRawResponse());
311 encoder.setSamlMessage(requestContext.getSamlResponse());
312 requestContext.setMessageEncoder(encoder);
316 } catch (BindingException e) {
317 throw new ProfileException("Unable to encode response to relying party: "
318 + requestContext.getRelyingPartyId(), e);
322 /** Represents the internal state of a Shibboleth SSO Request while it's being processed by the IdP. */
323 protected class ShibbolethSSORequestContext extends
324 SAML1ProfileRequestContext<SAMLObject, Response, ShibbolethSSOConfiguration> {
326 /** Current login context. */
327 private ShibbolethSSOLoginContext loginContext;
332 * @param request current profile request
333 * @param response current profile response
335 public ShibbolethSSORequestContext(ProfileRequest<ServletRequest> request,
336 ProfileResponse<ServletResponse> response) {
337 super(request, response);
341 * Gets the current login context.
343 * @return current login context
345 public ShibbolethSSOLoginContext getLoginContext() {
350 * Sets the current login context.
352 * @param context current login context
354 public void setLoginContext(ShibbolethSSOLoginContext context) {
355 loginContext = context;