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.util.ArrayList;
22 import javax.servlet.RequestDispatcher;
23 import javax.servlet.ServletException;
24 import javax.servlet.http.HttpServletRequest;
25 import javax.servlet.http.HttpServletResponse;
26 import javax.servlet.http.HttpSession;
28 import org.opensaml.common.SAMLObjectBuilder;
29 import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
30 import org.opensaml.common.xml.SAMLConstants;
31 import org.opensaml.saml1.core.AttributeStatement;
32 import org.opensaml.saml1.core.AuthenticationStatement;
33 import org.opensaml.saml1.core.Request;
34 import org.opensaml.saml1.core.Response;
35 import org.opensaml.saml1.core.Statement;
36 import org.opensaml.saml1.core.StatusCode;
37 import org.opensaml.saml1.core.Subject;
38 import org.opensaml.saml1.core.SubjectLocality;
39 import org.opensaml.saml2.metadata.AssertionConsumerService;
40 import org.opensaml.saml2.metadata.Endpoint;
41 import org.opensaml.saml2.metadata.EntityDescriptor;
42 import org.opensaml.saml2.metadata.IDPSSODescriptor;
43 import org.opensaml.saml2.metadata.SPSSODescriptor;
44 import org.opensaml.saml2.metadata.provider.MetadataProvider;
45 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
46 import org.opensaml.ws.message.decoder.MessageDecodingException;
47 import org.opensaml.ws.transport.http.HTTPInTransport;
48 import org.opensaml.ws.transport.http.HTTPOutTransport;
49 import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
50 import org.opensaml.ws.transport.http.HttpServletResponseAdapter;
51 import org.opensaml.xml.security.SecurityException;
52 import org.opensaml.xml.util.DatatypeHelper;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
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.ProfileConfiguration;
59 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
60 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml1.ShibbolethSSOConfiguration;
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 = LoggerFactory.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;
83 * @param authnManagerPath path to the authentication manager servlet
85 * @throws IllegalArgumentException thrown if either the authentication manager path or encoding binding URI are
88 public ShibbolethSSOProfileHandler(String authnManagerPath) {
89 if (DatatypeHelper.isEmpty(authnManagerPath)) {
90 throw new IllegalArgumentException("Authentication manager path may not be null");
92 authenticationManagerPath = authnManagerPath;
94 authnStatementBuilder = (SAMLObjectBuilder<AuthenticationStatement>) getBuilderFactory().getBuilder(
95 AuthenticationStatement.DEFAULT_ELEMENT_NAME);
97 subjectLocalityBuilder = (SAMLObjectBuilder<SubjectLocality>) getBuilderFactory().getBuilder(
98 SubjectLocality.DEFAULT_ELEMENT_NAME);
102 public String getProfileId() {
103 return "urn:mace:shibboleth:2.0:idp:profiles:shibboleth:request:sso";
107 public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
108 log.debug("Processing incomming request");
110 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
111 HttpSession httpSession = httpRequest.getSession();
112 LoginContext loginContext = (LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
114 if (loginContext == null) {
115 log.debug("User session does not contain a login context, processing as first leg of request");
116 performAuthentication(inTransport, outTransport);
117 } else if (!loginContext.isPrincipalAuthenticated()) {
119 .debug("User session contained a login context but user was not authenticated, processing as first leg of request");
120 performAuthentication(inTransport, outTransport);
122 log.debug("User session contains a login context, processing as second leg of request");
123 completeAuthenticationRequest(inTransport, outTransport);
128 * Creates a {@link LoginContext} an sends the request off to the AuthenticationManager to begin the process of
129 * authenticating the user.
131 * @param inTransport inbound message transport
132 * @param outTransport outbound message transport
134 * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
135 * authentication manager
137 protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
138 throws ProfileException {
140 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
141 HttpServletResponse httpResponse = ((HttpServletResponseAdapter) outTransport).getWrappedResponse();
142 HttpSession httpSession = httpRequest.getSession(true);
144 ShibbolethSSORequestContext requestContext = decodeRequest(inTransport, outTransport);
145 ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
147 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(loginContext.getRelyingPartyId());
148 ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID);
149 if (ssoConfig == null) {
150 log.error("Shibboleth SSO profile is not configured for relying party " + loginContext.getRelyingPartyId());
151 throw new ProfileException("Shibboleth SSO profile is not configured for relying party "
152 + loginContext.getRelyingPartyId());
154 loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
156 httpSession.setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
159 RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
160 dispatcher.forward(httpRequest, httpResponse);
162 } catch (IOException ex) {
163 httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
164 log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
165 throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
166 } catch (ServletException ex) {
167 httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
168 log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
169 throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
174 * Decodes an incoming request and populates a created request context with the resultant information.
176 * @param inTransport inbound message transport
177 * @param outTransport outbound message transport
179 * @return the created request context
181 * @throws ProfileException throw if there is a problem decoding the request
183 protected ShibbolethSSORequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
184 throws ProfileException {
185 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
187 ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
188 requestContext.setMetadataProvider(getMetadataProvider());
189 requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
191 requestContext.setCommunicationProfileId(ShibbolethSSOConfiguration.PROFILE_ID);
192 requestContext.setInboundMessageTransport(inTransport);
193 requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
194 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
196 requestContext.setOutboundMessageTransport(outTransport);
197 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML11P_NS);
199 SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
200 requestContext.setMessageDecoder(decoder);
202 decoder.decode(requestContext);
203 } catch (MessageDecodingException e) {
204 log.error("Error decoding Shibboleth SSO request", e);
205 throw new ProfileException("Error decoding Shibboleth SSO request", e);
206 } catch (SecurityException e) {
207 log.error("Shibboleth SSO request does not meet security requirements", e);
208 throw new ProfileException("Shibboleth SSO request does not meet security requirements", e);
211 ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
212 loginContext.setRelyingParty(requestContext.getInboundMessageIssuer());
213 loginContext.setSpAssertionConsumerService(requestContext.getSpAssertionConsumerService());
214 loginContext.setSpTarget(requestContext.getRelayState());
215 loginContext.setAuthenticationEngineURL(authenticationManagerPath);
216 loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
218 requestContext.setLoginContext(loginContext);
220 return requestContext;
224 * Creates a response to the Shibboleth SSO and sends the user, with response in tow, back to the relying party
225 * after they've been authenticated.
227 * @param inTransport inbound message transport
228 * @param outTransport outbound message transport
230 * @throws ProfileException thrown if the response can not be created and sent back to the relying party
232 protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
233 throws ProfileException {
234 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
235 HttpSession httpSession = httpRequest.getSession(true);
237 ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) httpSession
238 .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
239 httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
241 ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
243 Response samlResponse;
245 if (loginContext.getPrincipalName() == null) {
246 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "User failed authentication"));
247 throw new ProfileException("User failed authentication");
250 resolveAttributes(requestContext);
252 ArrayList<Statement> statements = new ArrayList<Statement>();
253 statements.add(buildAuthenticationStatement(requestContext));
254 if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
255 AttributeStatement attributeStatement = buildAttributeStatement(requestContext,
256 "urn:oasis:names:tc:SAML:1.0:cm:bearer");
257 if (attributeStatement != null) {
258 requestContext.setRequestedAttributes(requestContext.getPrincipalAttributes().keySet());
259 statements.add(attributeStatement);
263 samlResponse = buildResponse(requestContext, statements);
264 } catch (ProfileException e) {
265 samlResponse = buildErrorResponse(requestContext);
268 requestContext.setOutboundSAMLMessage(samlResponse);
269 requestContext.setOutboundSAMLMessageId(samlResponse.getID());
270 requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
271 encodeResponse(requestContext);
272 writeAuditLogEntry(requestContext);
276 * Creates an authentication request context from the current environmental information.
278 * @param loginContext current login context
279 * @param in inbound transport
280 * @param out outbount transport
282 * @return created authentication request context
284 * @throws ProfileException thrown if there is a problem creating the context
286 protected ShibbolethSSORequestContext buildRequestContext(ShibbolethSSOLoginContext loginContext,
287 HTTPInTransport in, HTTPOutTransport out) throws ProfileException {
288 ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
290 requestContext.setMessageDecoder(getMessageDecoders().get(getInboundBinding()));
292 requestContext.setLoginContext(loginContext);
293 requestContext.setPrincipalName(loginContext.getPrincipalName());
294 requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
295 requestContext.setUserSession(getUserSession(in));
296 requestContext.setRelayState(loginContext.getSpTarget());
298 requestContext.setInboundMessageTransport(in);
299 requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
301 requestContext.setOutboundMessageTransport(out);
302 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
304 MetadataProvider metadataProvider = getMetadataProvider();
305 requestContext.setMetadataProvider(metadataProvider);
307 String relyingPartyId = loginContext.getRelyingPartyId();
308 requestContext.setInboundMessageIssuer(relyingPartyId);
311 EntityDescriptor relyingPartyMetadata = metadataProvider.getEntityDescriptor(relyingPartyId);
312 if (relyingPartyMetadata != null) {
313 requestContext.setPeerEntityMetadata(relyingPartyMetadata);
314 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
315 requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata
316 .getSPSSODescriptor(SAMLConstants.SAML11P_NS));
318 } catch (MetadataProviderException e) {
319 log.error("Unable to locate metadata for relying party");
320 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
321 "Error locating relying party metadata"));
322 throw new ProfileException("Error locating relying party metadata");
325 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
326 if (rpConfig == null) {
327 log.error("Unable to retrieve relying party configuration data for entity with ID {}", relyingPartyId);
328 throw new ProfileException("Unable to retrieve relying party configuration data for entity with ID "
331 requestContext.setRelyingPartyConfiguration(rpConfig);
333 ShibbolethSSOConfiguration profileConfig = (ShibbolethSSOConfiguration) rpConfig
334 .getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID);
335 requestContext.setProfileConfiguration(profileConfig);
336 requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
337 if (profileConfig.getSigningCredential() != null) {
338 requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
339 } else if (rpConfig.getDefaultSigningCredential() != null) {
340 requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
343 requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
345 String assertingPartyId = rpConfig.getProviderId();
346 requestContext.setLocalEntityId(assertingPartyId);
348 EntityDescriptor localEntityDescriptor = metadataProvider.getEntityDescriptor(assertingPartyId);
349 if (localEntityDescriptor != null) {
350 requestContext.setLocalEntityMetadata(localEntityDescriptor);
351 requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
352 requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
353 .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
355 } catch (MetadataProviderException e) {
356 log.error("Unable to locate metadata for asserting party");
357 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
358 "Error locating asserting party metadata"));
359 throw new ProfileException("Error locating asserting party metadata");
362 return requestContext;
366 * Selects the appropriate endpoint for the relying party and stores it in the request context.
368 * @param requestContext current request context
370 * @return Endpoint selected from the information provided in the request context
372 protected Endpoint selectEndpoint(ShibbolethSSORequestContext requestContext) {
373 ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
375 ShibbolethSSOEndpointSelector endpointSelector = new ShibbolethSSOEndpointSelector();
376 endpointSelector.setSpAssertionConsumerService(loginContext.getSpAssertionConsumerService());
377 endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
378 endpointSelector.setMetadataProvider(getMetadataProvider());
379 endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
380 endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
381 endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
382 endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
384 return endpointSelector.selectEndpoint();
388 * Builds the authentication statement for the authenticated principal.
390 * @param requestContext current request context
392 * @return the created statement
394 * @throws ProfileException thrown if the authentication statement can not be created
396 protected AuthenticationStatement buildAuthenticationStatement(ShibbolethSSORequestContext requestContext)
397 throws ProfileException {
398 ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
400 AuthenticationStatement statement = authnStatementBuilder.buildObject();
401 statement.setAuthenticationInstant(loginContext.getAuthenticationInstant());
402 statement.setAuthenticationMethod(loginContext.getAuthenticationMethod());
404 statement.setSubjectLocality(buildSubjectLocality(requestContext));
406 Subject statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:bearer");
407 statement.setSubject(statementSubject);
413 * Constructs the subject locality for the authentication statement.
415 * @param requestContext curent request context
417 * @return subject locality for the authentication statement
419 protected SubjectLocality buildSubjectLocality(ShibbolethSSORequestContext requestContext) {
420 SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
422 HTTPInTransport inTransport = (HTTPInTransport) requestContext.getInboundMessageTransport();
423 subjectLocality.setIPAddress(inTransport.getPeerAddress());
424 subjectLocality.setDNSAddress(inTransport.getPeerDomainName());
426 return subjectLocality;
429 /** Represents the internal state of a Shibboleth SSO Request while it's being processed by the IdP. */
430 public class ShibbolethSSORequestContext extends
431 BaseSAML1ProfileRequestContext<Request, Response, ShibbolethSSOConfiguration> {
433 /** SP-provide assertion consumer service URL. */
434 private String spAssertionConsumerService;
436 /** Current login context. */
437 private ShibbolethSSOLoginContext loginContext;
440 * Gets the current login context.
442 * @return current login context
444 public ShibbolethSSOLoginContext getLoginContext() {
449 * Sets the current login context.
451 * @param context current login context
453 public void setLoginContext(ShibbolethSSOLoginContext context) {
454 loginContext = context;
458 * Gets the SP-provided assertion consumer service URL.
460 * @return SP-provided assertion consumer service URL
462 public String getSpAssertionConsumerService() {
463 return spAssertionConsumerService;
467 * Sets the SP-provided assertion consumer service URL.
469 * @param acs SP-provided assertion consumer service URL
471 public void setSpAssertionConsumerService(String acs) {
472 spAssertionConsumerService = acs;