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.AuthenticationStatement;
32 import org.opensaml.saml1.core.Request;
33 import org.opensaml.saml1.core.Response;
34 import org.opensaml.saml1.core.Statement;
35 import org.opensaml.saml1.core.StatusCode;
36 import org.opensaml.saml1.core.Subject;
37 import org.opensaml.saml1.core.SubjectLocality;
38 import org.opensaml.saml2.metadata.AssertionConsumerService;
39 import org.opensaml.saml2.metadata.Endpoint;
40 import org.opensaml.saml2.metadata.EntityDescriptor;
41 import org.opensaml.saml2.metadata.IDPSSODescriptor;
42 import org.opensaml.saml2.metadata.SPSSODescriptor;
43 import org.opensaml.saml2.metadata.provider.MetadataProvider;
44 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
45 import org.opensaml.ws.message.decoder.MessageDecodingException;
46 import org.opensaml.ws.transport.http.HTTPInTransport;
47 import org.opensaml.ws.transport.http.HTTPOutTransport;
48 import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
49 import org.opensaml.ws.transport.http.HttpServletResponseAdapter;
50 import org.opensaml.xml.security.SecurityException;
51 import org.opensaml.xml.util.DatatypeHelper;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
55 import edu.internet2.middleware.shibboleth.common.ShibbolethConstants;
56 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
57 import edu.internet2.middleware.shibboleth.common.relyingparty.ProfileConfiguration;
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.util.HttpHelper;
61 import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
62 import edu.internet2.middleware.shibboleth.idp.authn.ShibbolethSSOLoginContext;
64 /** Shibboleth SSO request profile handler. */
65 public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
68 private final Logger log = LoggerFactory.getLogger(ShibbolethSSOProfileHandler.class);
70 /** Builder of AuthenticationStatement objects. */
71 private SAMLObjectBuilder<AuthenticationStatement> authnStatementBuilder;
73 /** Builder of SubjectLocality objects. */
74 private SAMLObjectBuilder<SubjectLocality> subjectLocalityBuilder;
76 /** URL of the authentication manager servlet. */
77 private String authenticationManagerPath;
82 * @param authnManagerPath path to the authentication manager servlet
84 * @throws IllegalArgumentException thrown if either the authentication manager path or encoding binding URI are
87 public ShibbolethSSOProfileHandler(String authnManagerPath) {
88 if (DatatypeHelper.isEmpty(authnManagerPath)) {
89 throw new IllegalArgumentException("Authentication manager path may not be null");
91 authenticationManagerPath = authnManagerPath;
93 authnStatementBuilder = (SAMLObjectBuilder<AuthenticationStatement>) getBuilderFactory().getBuilder(
94 AuthenticationStatement.DEFAULT_ELEMENT_NAME);
96 subjectLocalityBuilder = (SAMLObjectBuilder<SubjectLocality>) getBuilderFactory().getBuilder(
97 SubjectLocality.DEFAULT_ELEMENT_NAME);
101 public String getProfileId() {
102 return "urn:mace:shibboleth:2.0:idp:profiles:shibboleth:request:sso";
106 public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
107 log.debug("Processing incomming request");
109 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
110 HttpSession httpSession = httpRequest.getSession();
112 if (httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY) == null) {
113 log.debug("User session does not contain a login context, processing as first leg of request");
114 performAuthentication(inTransport, outTransport);
116 log.debug("User session contains a login context, processing as second leg of request");
117 completeAuthenticationRequest(inTransport, outTransport);
122 * Creates a {@link LoginContext} an sends the request off to the AuthenticationManager to begin the process of
123 * authenticating the user.
125 * @param inTransport inbound message transport
126 * @param outTransport outbound message transport
128 * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
129 * authentication manager
131 protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
132 throws ProfileException {
134 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
135 HttpServletResponse httpResponse = ((HttpServletResponseAdapter) outTransport).getWrappedResponse();
136 HttpSession httpSession = httpRequest.getSession(true);
138 ShibbolethSSORequestContext requestContext = decodeRequest(inTransport, outTransport);
139 ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
141 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(loginContext.getRelyingPartyId());
142 ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID);
143 if (ssoConfig == null) {
144 log.error("Shibboleth SSO profile is not configured for relying party " + loginContext.getRelyingPartyId());
145 throw new ProfileException("Shibboleth SSO profile is not configured for relying party "
146 + loginContext.getRelyingPartyId());
148 loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
150 httpSession.setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
153 RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
154 dispatcher.forward(httpRequest, httpResponse);
156 } catch (IOException ex) {
157 log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
158 throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
159 } catch (ServletException ex) {
160 log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
161 throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
166 * Decodes an incoming request and populates a created request context with the resultant information.
168 * @param inTransport inbound message transport
169 * @param outTransport outbound message transport
171 * @return the created request context
173 * @throws ProfileException throw if there is a problem decoding the request
175 protected ShibbolethSSORequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
176 throws ProfileException {
177 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
179 ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
180 requestContext.setMetadataProvider(getMetadataProvider());
182 requestContext.setCommunicationProfileId(ShibbolethSSOConfiguration.PROFILE_ID);
183 requestContext.setInboundMessageTransport(inTransport);
184 requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
185 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
187 requestContext.setOutboundMessageTransport(outTransport);
188 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML11P_NS);
190 SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
191 requestContext.setMessageDecoder(decoder);
193 decoder.decode(requestContext);
194 } catch (MessageDecodingException e) {
195 log.error("Error decoding Shibboleth SSO request", e);
196 throw new ProfileException("Error decoding Shibboleth SSO request", e);
197 } catch (SecurityException e) {
198 log.error("Shibboleth SSO request does not meet security requirements", e);
199 throw new ProfileException("Shibboleth SSO request does not meet security requirements", e);
202 ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
203 loginContext.setRelyingParty(requestContext.getInboundMessageIssuer());
204 loginContext.setSpAssertionConsumerService(requestContext.getSpAssertionConsumerService());
205 loginContext.setSpTarget(requestContext.getRelayState());
206 loginContext.setAuthenticationEngineURL(authenticationManagerPath);
207 loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
209 requestContext.setLoginContext(loginContext);
211 return requestContext;
215 * Creates a response to the Shibboleth SSO and sends the user, with response in tow, back to the relying party
216 * after they've been authenticated.
218 * @param inTransport inbound message transport
219 * @param outTransport outbound message transport
221 * @throws ProfileException thrown if the response can not be created and sent back to the relying party
223 protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
224 throws ProfileException {
225 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
226 HttpSession httpSession = httpRequest.getSession(true);
228 ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) httpSession
229 .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
230 httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
232 ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
234 Response samlResponse;
236 if (loginContext.getPrincipalName() == null) {
237 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "User failed authentication"));
238 throw new ProfileException("User failed authentication");
241 resolveAttributes(requestContext);
243 ArrayList<Statement> statements = new ArrayList<Statement>();
244 statements.add(buildAuthenticationStatement(requestContext));
245 if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
246 requestContext.setRequestedAttributes(requestContext.getPrincipalAttributes().keySet());
247 statements.add(buildAttributeStatement(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:bearer"));
250 samlResponse = buildResponse(requestContext, statements);
251 } catch (ProfileException e) {
252 samlResponse = buildErrorResponse(requestContext);
255 requestContext.setOutboundSAMLMessage(samlResponse);
256 requestContext.setOutboundSAMLMessageId(samlResponse.getID());
257 requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
258 encodeResponse(requestContext);
259 writeAuditLogEntry(requestContext);
263 * Creates an authentication request context from the current environmental information.
265 * @param loginContext current login context
266 * @param in inbound transport
267 * @param out outbount transport
269 * @return created authentication request context
271 * @throws ProfileException thrown if there is a problem creating the context
273 protected ShibbolethSSORequestContext buildRequestContext(ShibbolethSSOLoginContext loginContext,
274 HTTPInTransport in, HTTPOutTransport out) throws ProfileException {
275 ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
278 requestContext.setMessageDecoder(getMessageDecoders().get(getInboundBinding()));
280 requestContext.setLoginContext(loginContext);
281 requestContext.setPrincipalName(loginContext.getPrincipalName());
282 requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
283 requestContext.setUserSession(getUserSession(in));
284 requestContext.setRelayState(loginContext.getSpTarget());
286 requestContext.setInboundMessageTransport(in);
287 requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
289 MetadataProvider metadataProvider = getMetadataProvider();
290 requestContext.setMetadataProvider(metadataProvider);
292 String relyingPartyId = loginContext.getRelyingPartyId();
293 requestContext.setInboundMessageIssuer(relyingPartyId);
294 EntityDescriptor relyingPartyMetadata = metadataProvider.getEntityDescriptor(relyingPartyId);
295 requestContext.setPeerEntityMetadata(relyingPartyMetadata);
296 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
297 requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML11P_NS));
298 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
299 requestContext.setRelyingPartyConfiguration(rpConfig);
300 requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
302 String assertingPartyId = rpConfig.getProviderId();
303 requestContext.setLocalEntityId(assertingPartyId);
304 EntityDescriptor assertingPartyMetadata = metadataProvider.getEntityDescriptor(assertingPartyId);
305 requestContext.setLocalEntityMetadata(assertingPartyMetadata);
306 requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
307 requestContext.setLocalEntityRoleMetadata(assertingPartyMetadata
308 .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
310 requestContext.setOutboundMessageTransport(out);
311 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
312 ShibbolethSSOConfiguration profileConfig = (ShibbolethSSOConfiguration) rpConfig
313 .getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID);
314 requestContext.setProfileConfiguration(profileConfig);
315 requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
316 if (profileConfig.getSigningCredential() != null) {
317 requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
318 } else if (rpConfig.getDefaultSigningCredential() != null) {
319 requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
322 return requestContext;
323 } catch (MetadataProviderException e) {
324 log.error("Unable to locate metadata for asserting or relying party");
325 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error locating party metadata"));
326 throw new ProfileException("Error locating party metadata");
331 * Selects the appropriate endpoint for the relying party and stores it in the request context.
333 * @param requestContext current request context
335 * @return Endpoint selected from the information provided in the request context
337 protected Endpoint selectEndpoint(ShibbolethSSORequestContext requestContext) {
338 ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
340 ShibbolethSSOEndpointSelector endpointSelector = new ShibbolethSSOEndpointSelector();
341 endpointSelector.setSpAssertionConsumerService(loginContext.getSpAssertionConsumerService());
342 endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
343 endpointSelector.setMetadataProvider(getMetadataProvider());
344 endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
345 endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
346 endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
347 endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
349 return endpointSelector.selectEndpoint();
353 * Builds the authentication statement for the authenticated principal.
355 * @param requestContext current request context
357 * @return the created statement
359 * @throws ProfileException thrown if the authentication statement can not be created
361 protected AuthenticationStatement buildAuthenticationStatement(ShibbolethSSORequestContext requestContext)
362 throws ProfileException {
363 ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
365 AuthenticationStatement statement = authnStatementBuilder.buildObject();
366 statement.setAuthenticationInstant(loginContext.getAuthenticationInstant());
367 statement.setAuthenticationMethod(loginContext.getAuthenticationMethod());
369 statement.setSubjectLocality(buildSubjectLocality(requestContext));
371 Subject statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:bearer");
372 statement.setSubject(statementSubject);
378 * Constructs the subject locality for the authentication statement.
380 * @param requestContext curent request context
382 * @return subject locality for the authentication statement
384 protected SubjectLocality buildSubjectLocality(ShibbolethSSORequestContext requestContext) {
385 SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
387 HTTPInTransport inTransport = (HTTPInTransport) requestContext.getInboundMessageTransport();
388 subjectLocality.setIPAddress(inTransport.getPeerAddress());
389 subjectLocality.setDNSAddress(inTransport.getPeerDomainName());
391 return subjectLocality;
394 /** Represents the internal state of a Shibboleth SSO Request while it's being processed by the IdP. */
395 public class ShibbolethSSORequestContext extends
396 BaseSAML1ProfileRequestContext<Request, Response, ShibbolethSSOConfiguration> {
398 /** SP-provide assertion consumer service URL. */
399 private String spAssertionConsumerService;
401 /** Current login context. */
402 private ShibbolethSSOLoginContext loginContext;
405 * Gets the current login context.
407 * @return current login context
409 public ShibbolethSSOLoginContext getLoginContext() {
414 * Sets the current login context.
416 * @param context current login context
418 public void setLoginContext(ShibbolethSSOLoginContext context) {
419 loginContext = context;
423 * Gets the SP-provided assertion consumer service URL.
425 * @return SP-provided assertion consumer service URL
427 public String getSpAssertionConsumerService() {
428 return spAssertionConsumerService;
432 * Sets the SP-provided assertion consumer service URL.
434 * @param acs SP-provided assertion consumer service URL
436 public void setSpAssertionConsumerService(String acs) {
437 spAssertionConsumerService = acs;