Configuration code for SAML 2 SSO profile handler
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml2 / AttributeQueryProfileHandler.java
1 /*
2  * Copyright [2006] [University Corporation for Advanced Internet Development, Inc.]
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 package edu.internet2.middleware.shibboleth.idp.profile.saml2;
18
19 import java.util.ArrayList;
20
21 import javax.servlet.ServletRequest;
22 import javax.servlet.ServletResponse;
23
24 import org.apache.log4j.Logger;
25 import org.opensaml.common.binding.BindingException;
26 import org.opensaml.common.binding.decoding.MessageDecoder;
27 import org.opensaml.common.binding.encoding.MessageEncoder;
28 import org.opensaml.common.binding.security.SAMLSecurityPolicy;
29 import org.opensaml.saml2.binding.decoding.HTTPSOAP11Decoder;
30 import org.opensaml.saml2.core.AttributeQuery;
31 import org.opensaml.saml2.core.Response;
32 import org.opensaml.saml2.core.Statement;
33 import org.opensaml.saml2.core.StatusCode;
34 import org.opensaml.saml2.core.Subject;
35 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
36 import org.opensaml.saml2.metadata.SPSSODescriptor;
37 import org.opensaml.ws.security.SecurityPolicyException;
38
39 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
40 import edu.internet2.middleware.shibboleth.common.profile.ProfileRequest;
41 import edu.internet2.middleware.shibboleth.common.profile.ProfileResponse;
42 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
43 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.AttributeQueryConfiguration;
44
45 /**
46  * SAML 2.0 Attribute Query profile handler.
47  */
48 public class AttributeQueryProfileHandler extends AbstractSAML2ProfileHandler {
49
50     /** Class logger. */
51     private static Logger log = Logger.getLogger(AttributeQueryProfileHandler.class);
52
53     /** SAML binding URI. */
54     private static final String BINDING = "urn:oasis:names:tc:SAML:2.0:bindings:SOAP";
55
56     /** {@inheritDoc} */
57     public String getProfileId() {
58         return "urn:mace:shibboleth:2.0:idp:profiles:saml2:query:attribute";
59     }
60
61     /** {@inheritDoc} */
62     public void processRequest(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response)
63             throws ProfileException {
64
65         AttributeQueryContext requestContext = new AttributeQueryContext(request, response);
66
67         Response samlResponse;
68         try {
69             decodeRequest(requestContext);
70
71             // Lookup principal name and attributes, create attribute statement from information
72             ArrayList<Statement> statements = new ArrayList<Statement>();
73             statements.add(buildAttributeStatement(requestContext));
74
75             // create the assertion subject
76             Subject assertionSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:sender-vouches");
77
78             // create the SAML response
79             samlResponse = buildResponse(requestContext, assertionSubject, statements);
80         } catch (ProfileException e) {
81             samlResponse = buildErrorResponse(requestContext);
82         }
83
84         requestContext.setSamlResponse(samlResponse);
85
86         encodeResponse(requestContext);
87         writeAuditLogEntry(requestContext);
88     }
89
90     /**
91      * Decodes the message in the request and adds it to the request context.
92      * 
93      * @param requestContext request context contianing the request to decode
94      * 
95      * @throws ProfileException throw if there is a problem decoding the request
96      */
97     protected void decodeRequest(AttributeQueryContext requestContext) throws ProfileException {
98         if (log.isDebugEnabled()) {
99             log.debug("Decoding incomming request");
100         }
101         MessageDecoder<ServletRequest> decoder = getMessageDecoderFactory().getMessageDecoder(
102                 HTTPSOAP11Decoder.BINDING_URI);
103         if (decoder == null) {
104             throw new ProfileException("No request decoder was registered for binding type: "
105                     + HTTPSOAP11Decoder.BINDING_URI);
106         }
107         super.populateMessageDecoder(decoder);
108
109         decoder.setRequest(requestContext.getProfileRequest().getRawRequest());
110         requestContext.setMessageDecoder(decoder);
111
112         try {
113             decoder.decode();
114             if (log.isDebugEnabled()) {
115                 log.debug("Decoded request");
116             }
117         } catch (BindingException e) {
118             log.error("Error decoding attribute query message", e);
119             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error decoding message"));
120             throw new ProfileException("Error decoding attribute query message");
121         } catch (SecurityPolicyException e) {
122             log.error("Message did not meet security policy requirements", e);
123             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
124                     "Message did not meet security policy requirements"));
125             throw new ProfileException("Message did not meet security policy requirements", e);
126         } finally {
127             // Set as much information as can be retrieved from the decoded message
128             SAMLSecurityPolicy securityPolicy = requestContext.getMessageDecoder().getSecurityPolicy();
129             requestContext.setRelyingPartyId(securityPolicy.getIssuer());
130
131             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(requestContext.getRelyingPartyId());
132             requestContext.setRelyingPartyConfiguration(rpConfig);
133
134             requestContext.setRelyingPartyRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
135
136             requestContext.setAssertingPartyId(requestContext.getRelyingPartyConfiguration().getProviderId());
137
138             requestContext.setAssertingPartyRole(AttributeAuthorityDescriptor.DEFAULT_ELEMENT_NAME);
139
140             requestContext.setProfileConfiguration((AttributeQueryConfiguration) rpConfig
141                     .getProfileConfiguration(AttributeQueryConfiguration.PROFILE_ID));
142
143             requestContext.setSamlRequest((AttributeQuery) requestContext.getMessageDecoder().getSAMLMessage());
144         }
145     }
146
147     /**
148      * Encodes the request's SAML response and writes it to the servlet response.
149      * 
150      * @param requestContext current request context
151      * 
152      * @throws ProfileException thrown if no message encoder is registered for this profiles binding
153      */
154     protected void encodeResponse(AttributeQueryContext requestContext) throws ProfileException {
155         if (log.isDebugEnabled()) {
156             log.debug("Encoding response to SAML request " + requestContext.getSamlRequest().getID()
157                     + " from relying party " + requestContext.getRelyingPartyId());
158         }
159         MessageEncoder<ServletResponse> encoder = getMessageEncoderFactory().getMessageEncoder(BINDING);
160         if (encoder == null) {
161             throw new ProfileException("No response encoder was registered for binding type: " + BINDING);
162         }
163
164         super.populateMessageEncoder(encoder);
165         encoder.setResponse(requestContext.getProfileResponse().getRawResponse());
166         encoder.setSamlMessage(requestContext.getSamlResponse());
167         requestContext.setMessageEncoder(encoder);
168
169         try {
170             encoder.encode();
171         } catch (BindingException e) {
172             throw new ProfileException("Unable to encode response to relying party: "
173                     + requestContext.getRelyingPartyId(), e);
174         }
175     }
176
177     /** Basic data structure used to accumulate information as a request is being processed. */
178     protected class AttributeQueryContext extends
179             SAML2ProfileRequestContext<AttributeQuery, Response, AttributeQueryConfiguration> {
180
181         /**
182          * Constructor.
183          * 
184          * @param request current profile request
185          * @param response current profile response
186          */
187         public AttributeQueryContext(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response) {
188             super(request, response);
189         }
190     }
191 }