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;
23 import java.util.List;
25 import javax.servlet.RequestDispatcher;
26 import javax.servlet.ServletException;
27 import javax.servlet.http.HttpServletRequest;
28 import javax.servlet.http.HttpServletResponse;
29 import javax.servlet.http.HttpSession;
31 import org.apache.log4j.Logger;
32 import org.opensaml.common.SAMLObjectBuilder;
33 import org.opensaml.common.binding.BasicEndpointSelector;
34 import org.opensaml.common.xml.SAMLConstants;
35 import org.opensaml.saml1.core.AuthenticationStatement;
36 import org.opensaml.saml1.core.Request;
37 import org.opensaml.saml1.core.Response;
38 import org.opensaml.saml1.core.Statement;
39 import org.opensaml.saml1.core.StatusCode;
40 import org.opensaml.saml1.core.Subject;
41 import org.opensaml.saml1.core.SubjectLocality;
42 import org.opensaml.saml2.metadata.AssertionConsumerService;
43 import org.opensaml.saml2.metadata.Endpoint;
44 import org.opensaml.saml2.metadata.EntityDescriptor;
45 import org.opensaml.saml2.metadata.IDPSSODescriptor;
46 import org.opensaml.saml2.metadata.SPSSODescriptor;
47 import org.opensaml.saml2.metadata.provider.MetadataProvider;
48 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
49 import org.opensaml.ws.message.encoder.MessageEncodingException;
50 import org.opensaml.ws.transport.http.HTTPInTransport;
51 import org.opensaml.ws.transport.http.HTTPOutTransport;
52 import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
53 import org.opensaml.ws.transport.http.HttpServletResponseAdapter;
54 import org.opensaml.xml.util.DatatypeHelper;
56 import edu.internet2.middleware.shibboleth.common.ShibbolethConstants;
57 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
58 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
59 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml1.ShibbolethSSOConfiguration;
60 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.SSOConfiguration;
61 import edu.internet2.middleware.shibboleth.common.util.HttpHelper;
62 import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
63 import edu.internet2.middleware.shibboleth.idp.authn.ShibbolethSSOLoginContext;
65 /** Shibboleth SSO request profile handler. */
66 public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
69 private final Logger log = Logger.getLogger(ShibbolethSSOProfileHandler.class);
71 /** Builder of AuthenticationStatement objects. */
72 private SAMLObjectBuilder<AuthenticationStatement> authnStatementBuilder;
74 /** Builder of SubjectLocality objects. */
75 private SAMLObjectBuilder<SubjectLocality> subjectLocalityBuilder;
77 /** URL of the authentication manager servlet. */
78 private String authenticationManagerPath;
80 /** URI of SAML 1 bindings supported for outgoing message encoding. */
81 private ArrayList<String> supportedOutgoingBindings;
86 * @param authnManagerPath path to the authentication manager servlet
87 * @param outgoingBindings URIs of SAML 1 bindings supported for outgoing message encoding
89 * @throws IllegalArgumentException thrown if either the authentication manager path or encoding binding URI are
92 public ShibbolethSSOProfileHandler(String authnManagerPath, List<String> outgoingBindings) {
93 if (DatatypeHelper.isEmpty(authnManagerPath)) {
94 throw new IllegalArgumentException("Authentication manager path may not be null");
96 authenticationManagerPath = authnManagerPath;
98 if (outgoingBindings == null || outgoingBindings.isEmpty()) {
99 throw new IllegalArgumentException("List of supported outgoing bindings may not be empty");
101 supportedOutgoingBindings = new ArrayList<String>(outgoingBindings);
103 authnStatementBuilder = (SAMLObjectBuilder<AuthenticationStatement>) getBuilderFactory().getBuilder(
104 AuthenticationStatement.DEFAULT_ELEMENT_NAME);
106 subjectLocalityBuilder = (SAMLObjectBuilder<SubjectLocality>) getBuilderFactory().getBuilder(
107 SubjectLocality.DEFAULT_ELEMENT_NAME);
111 public String getProfileId() {
112 return "urn:mace:shibboleth:2.0:idp:profiles:shibboleth:request:sso";
116 public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
117 if (log.isDebugEnabled()) {
118 log.debug("Processing incomming request");
121 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
122 HttpSession httpSession = httpRequest.getSession();
124 if (httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY) == null) {
125 if (log.isDebugEnabled()) {
126 log.debug("User session does not contain a login context, processing as first leg of request");
128 performAuthentication(inTransport, outTransport);
130 if (log.isDebugEnabled()) {
131 log.debug("User session contains a login context, processing as second leg of request");
133 completeAuthenticationRequest(inTransport, outTransport);
138 * Creates a {@link LoginContext} an sends the request off to the AuthenticationManager to begin the process of
139 * authenticating the user.
141 * @param inTransport inbound message transport
142 * @param outTransport outbound message transport
144 * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
145 * authentication manager
147 protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
148 throws ProfileException {
150 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
151 HttpServletResponse httpResponse = ((HttpServletResponseAdapter) outTransport).getWrappedResponse();
152 HttpSession httpSession = httpRequest.getSession(true);
154 LoginContext loginContext = buildLoginContext(httpRequest);
155 if (getRelyingPartyConfiguration(loginContext.getRelyingPartyId()) == null) {
156 log.error("Shibboleth SSO profile is not configured for relying party " + loginContext.getRelyingPartyId());
157 throw new ProfileException("Shibboleth SSO profile is not configured for relying party "
158 + loginContext.getRelyingPartyId());
161 httpSession.setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
164 RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
165 dispatcher.forward(httpRequest, httpResponse);
167 } catch (IOException ex) {
168 log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
169 throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
170 } catch (ServletException ex) {
171 log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
172 throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
177 * Creates a response to the Shibboleth SSO and sends the user, with response in tow, back to the relying party
178 * after they've been authenticated.
180 * @param inTransport inbound message transport
181 * @param outTransport outbound message transport
183 * @throws ProfileException thrown if the response can not be created and sent back to the relying party
185 protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
186 throws ProfileException {
187 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
188 HttpSession httpSession = httpRequest.getSession(true);
190 ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) httpSession
191 .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
192 httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
194 ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
196 Response samlResponse;
198 if (loginContext.getPrincipalName() == null) {
199 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "User failed authentication"));
200 throw new ProfileException("User failed authentication");
203 resolveAttributes(requestContext);
205 ArrayList<Statement> statements = new ArrayList<Statement>();
206 statements.add(buildAuthenticationStatement(requestContext));
207 if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
208 statements.add(buildAttributeStatement(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:bearer"));
211 samlResponse = buildResponse(requestContext, statements);
212 } catch (ProfileException e) {
213 samlResponse = buildErrorResponse(requestContext);
216 requestContext.setOutboundSAMLMessage(samlResponse);
217 requestContext.setOutboundSAMLMessageId(samlResponse.getID());
218 requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
219 encodeResponse(requestContext);
220 writeAuditLogEntry(requestContext);
224 * Creates a login context from the incoming HTTP request.
226 * @param request current HTTP request
228 * @return the constructed login context
230 * @throws ProfileException thrown if the incomming request did not contain a providerId, shire, and target
233 protected ShibbolethSSOLoginContext buildLoginContext(HttpServletRequest request) throws ProfileException {
234 ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
237 String providerId = DatatypeHelper.safeTrimOrNullString(request.getParameter("providerId"));
238 if (providerId == null) {
239 log.error("No providerId parameter in Shibboleth SSO request");
240 throw new ProfileException("No providerId parameter in Shibboleth SSO request");
242 loginContext.setRelyingParty(URLDecoder.decode(providerId, "UTF-8"));
244 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(providerId);
245 if (rpConfig == null) {
246 log.error("No relying party configuration available for " + providerId);
247 throw new ProfileException("No relying party configuration available for " + providerId);
249 loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
251 String acs = DatatypeHelper.safeTrimOrNullString(request.getParameter("shire"));
253 log.error("No shire parameter in Shibboleth SSO request");
254 throw new ProfileException("No shire parameter in Shibboleth SSO request");
256 loginContext.setSpAssertionConsumerService(URLDecoder.decode(acs, "UTF-8"));
258 String target = DatatypeHelper.safeTrimOrNullString(request.getParameter("target"));
259 if (target == null) {
260 log.error("No target parameter in Shibboleth SSO request");
261 throw new ProfileException("No target parameter in Shibboleth SSO request");
263 loginContext.setSpTarget(URLDecoder.decode(target, "UTF-8"));
264 } catch (UnsupportedEncodingException e) {
265 // UTF-8 encoding required to be supported by all JVMs.
268 loginContext.setAuthenticationEngineURL(authenticationManagerPath);
269 loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(request));
274 * Creates an authentication request context from the current environmental information.
276 * @param loginContext current login context
277 * @param in inbound transport
278 * @param out outbount transport
280 * @return created authentication request context
282 * @throws ProfileException thrown if there is a problem creating the context
284 protected ShibbolethSSORequestContext buildRequestContext(ShibbolethSSOLoginContext loginContext,
285 HTTPInTransport in, HTTPOutTransport out) throws ProfileException {
286 ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
289 requestContext.setLoginContext(loginContext);
290 requestContext.setPrincipalName(loginContext.getPrincipalName());
291 requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
292 requestContext.setUserSession(getUserSession(in));
293 requestContext.setRelayState(loginContext.getSpTarget());
295 requestContext.setMessageInTransport(in);
296 requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
298 MetadataProvider metadataProvider = getMetadataProvider();
299 requestContext.setMetadataProvider(metadataProvider);
301 String relyingPartyId = loginContext.getRelyingPartyId();
302 requestContext.setRelyingPartyEntityId(relyingPartyId);
303 EntityDescriptor relyingPartyMetadata = metadataProvider.getEntityDescriptor(relyingPartyId);
304 requestContext.setPeerEntityMetadata(relyingPartyMetadata);
305 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
306 requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata
307 .getSPSSODescriptor(SAMLConstants.SAML11P_NS));
308 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
309 requestContext.setRelyingPartyConfiguration(rpConfig);
310 requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
312 String assertingPartyId = rpConfig.getProviderId();
313 requestContext.setAssertingPartyEntityId(assertingPartyId);
314 EntityDescriptor assertingPartyMetadata = metadataProvider.getEntityDescriptor(assertingPartyId);
315 requestContext.setLocalEntityMetadata(assertingPartyMetadata);
316 requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
317 requestContext.setLocalEntityRoleMetadata(assertingPartyMetadata
318 .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
320 requestContext.setMessageOutTransport(out);
321 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
322 ShibbolethSSOConfiguration profileConfig = (ShibbolethSSOConfiguration) rpConfig
323 .getProfileConfiguration(SSOConfiguration.PROFILE_ID);
324 requestContext.setProfileConfiguration(profileConfig);
325 if (profileConfig.getSigningCredential() != null) {
326 requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
327 } else if (rpConfig.getDefaultSigningCredential() != null) {
328 requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
331 return requestContext;
332 } catch (MetadataProviderException e) {
333 log.error("Unable to locate metadata for asserting or relying party");
334 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error locating party metadata"));
335 throw new ProfileException("Error locating party metadata");
340 * Selects the appropriate endpoint for the relying party and stores it in the request context.
342 * @param requestContext current request context
344 * @return Endpoint selected from the information provided in the request context
346 protected Endpoint selectEndpoint(ShibbolethSSORequestContext requestContext) {
347 ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
349 if (loginContext.getSpAssertionConsumerService() != null) {
350 SAMLObjectBuilder<AssertionConsumerService> acsBuilder = (SAMLObjectBuilder<AssertionConsumerService>) getBuilderFactory()
351 .getBuilder(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
352 AssertionConsumerService acsEndpoint = acsBuilder.buildObject();
353 acsEndpoint.setBinding(getMessageEncoder().getBindingURI());
354 acsEndpoint.setLocation(loginContext.getSpAssertionConsumerService());
358 BasicEndpointSelector endpointSelector = new BasicEndpointSelector();
359 endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
360 endpointSelector.setMetadataProvider(getMetadataProvider());
361 endpointSelector.setRelyingParty(requestContext.getPeerEntityMetadata());
362 endpointSelector.setRelyingPartyRole(requestContext.getPeerEntityRoleMetadata());
363 endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
364 endpointSelector.getSupportedIssuerBindings().addAll(supportedOutgoingBindings);
365 return endpointSelector.selectEndpoint();
369 * Builds the authentication statement for the authenticated principal.
371 * @param requestContext current request context
373 * @return the created statement
375 * @throws ProfileException thrown if the authentication statement can not be created
377 protected AuthenticationStatement buildAuthenticationStatement(ShibbolethSSORequestContext requestContext)
378 throws ProfileException {
379 ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
381 AuthenticationStatement statement = authnStatementBuilder.buildObject();
382 statement.setAuthenticationInstant(loginContext.getAuthenticationInstant());
383 statement.setAuthenticationMethod(loginContext.getAuthenticationMethod());
385 statement.setSubjectLocality(buildSubjectLocality(requestContext));
387 Subject statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:bearer");
388 statement.setSubject(statementSubject);
394 * Constructs the subject locality for the authentication statement.
396 * @param requestContext curent request context
398 * @return subject locality for the authentication statement
400 protected SubjectLocality buildSubjectLocality(ShibbolethSSORequestContext requestContext) {
401 SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
403 HTTPInTransport inTransport = (HTTPInTransport) requestContext.getMessageInTransport();
404 subjectLocality.setIPAddress(inTransport.getPeerAddress());
405 subjectLocality.setDNSAddress(inTransport.getPeerDomainName());
407 return subjectLocality;
411 * Encodes the request's SAML response and writes it to the servlet response.
413 * @param requestContext current request context
415 * @throws ProfileException thrown if no message encoder is registered for this profiles binding
417 protected void encodeResponse(ShibbolethSSORequestContext requestContext) throws ProfileException {
418 if (log.isDebugEnabled()) {
419 log.debug("Encoding response to SAML request " + requestContext.getInboundSAMLMessageId()
420 + " from relying party " + requestContext.getRelyingPartyEntityId());
424 getMessageEncoder().encode(requestContext);
425 } catch (MessageEncodingException e) {
426 throw new ProfileException("Unable to encode response to relying party: "
427 + requestContext.getRelyingPartyEntityId(), e);
431 /** Represents the internal state of a Shibboleth SSO Request while it's being processed by the IdP. */
432 protected class ShibbolethSSORequestContext extends
433 BaseSAML1ProfileRequestContext<Request, Response, ShibbolethSSOConfiguration> {
435 /** Current login context. */
436 private ShibbolethSSOLoginContext loginContext;
439 * Gets the current login context.
441 * @return current login context
443 public ShibbolethSSOLoginContext getLoginContext() {
448 * Sets the current login context.
450 * @param context current login context
452 public void setLoginContext(ShibbolethSSOLoginContext context) {
453 loginContext = context;