001: /* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
002: *
003: * Licensed under the Apache License, Version 2.0 (the "License");
004: * you may not use this file except in compliance with the License.
005: * You may obtain a copy of the License at
006: *
007: * http://www.apache.org/licenses/LICENSE-2.0
008: *
009: * Unless required by applicable law or agreed to in writing, software
010: * distributed under the License is distributed on an "AS IS" BASIS,
011: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012: * See the License for the specific language governing permissions and
013: * limitations under the License.
014: */
015:
016: package org.acegisecurity.ui.x509;
017:
018: import org.acegisecurity.Authentication;
019: import org.acegisecurity.AuthenticationException;
020: import org.acegisecurity.AuthenticationManager;
021:
022: import org.acegisecurity.context.SecurityContextHolder;
023:
024: import org.acegisecurity.event.authentication.InteractiveAuthenticationSuccessEvent;
025:
026: import org.acegisecurity.providers.x509.X509AuthenticationToken;
027:
028: import org.acegisecurity.ui.AbstractProcessingFilter;
029: import org.acegisecurity.ui.AuthenticationDetailsSource;
030: import org.acegisecurity.ui.AuthenticationDetailsSourceImpl;
031:
032: import org.apache.commons.logging.Log;
033: import org.apache.commons.logging.LogFactory;
034:
035: import org.springframework.beans.factory.InitializingBean;
036:
037: import org.springframework.context.ApplicationEventPublisher;
038: import org.springframework.context.ApplicationEventPublisherAware;
039:
040: import org.springframework.util.Assert;
041:
042: import java.io.IOException;
043:
044: import java.security.cert.X509Certificate;
045:
046: import javax.servlet.http.HttpServletRequest;
047: import javax.servlet.http.HttpServletResponse;
048: import javax.servlet.Filter;
049: import javax.servlet.ServletRequest;
050: import javax.servlet.ServletException;
051: import javax.servlet.FilterChain;
052: import javax.servlet.ServletResponse;
053: import javax.servlet.FilterConfig;
054:
055: /**
056: * Processes the X.509 certificate submitted by a client browser when HTTPS is used with client-authentication
057: * enabled.<p>An {@link X509AuthenticationToken} is created with the certificate as the credentials.</p>
058: * <p>The configured authentication manager is expected to supply a provider which can handle this token (usually
059: * an instance of {@link org.acegisecurity.providers.x509.X509AuthenticationProvider}).</p>
060: * <p>If authentication is successful, an {@link
061: * org.acegisecurity.event.authentication.InteractiveAuthenticationSuccessEvent} will be published to the application
062: * context. No events will be published if authentication was unsuccessful, because this would generally be recorded
063: * via an <code>AuthenticationManager</code>-specific application event.</p>
064: * <p><b>Do not use this class directly.</b> Instead configure <code>web.xml</code> to use the {@link
065: * org.acegisecurity.util.FilterToBeanProxy}.</p>
066: *
067: * @author Luke Taylor
068: * @version $Id: X509ProcessingFilter.java 1784 2007-02-24 21:00:24Z luke_t $
069: */
070: public class X509ProcessingFilter implements Filter, InitializingBean,
071: ApplicationEventPublisherAware {
072: //~ Static fields/initializers =====================================================================================
073:
074: private static final Log logger = LogFactory
075: .getLog(X509ProcessingFilter.class);
076:
077: //~ Instance fields ================================================================================================
078:
079: private ApplicationEventPublisher eventPublisher;
080: private AuthenticationDetailsSource authenticationDetailsSource = new AuthenticationDetailsSourceImpl();
081: private AuthenticationManager authenticationManager;
082:
083: //~ Methods ========================================================================================================
084:
085: public void afterPropertiesSet() throws Exception {
086: Assert.notNull(authenticationManager,
087: "An AuthenticationManager must be set");
088: }
089:
090: public void destroy() {
091: }
092:
093: /**
094: * This method first checks for an existing, non-null authentication in the secure context. If one is found
095: * it does nothing.<p>If no authentication object exists, it attempts to obtain the client authentication
096: * certificate from the request. If there is no certificate present then authentication is skipped. Otherwise a
097: * new authentication request containing the certificate will be passed to the configured {@link
098: * AuthenticationManager}.</p>
099: * <p>If authentication is successful the returned token will be stored in the secure context. Otherwise
100: * it will be set to null. In either case, the request proceeds through the filter chain.</p>
101: *
102: * @param request DOCUMENT ME!
103: * @param response DOCUMENT ME!
104: * @param filterChain DOCUMENT ME!
105: *
106: * @throws IOException DOCUMENT ME!
107: * @throws javax.servlet.ServletException DOCUMENT ME!
108: */
109: public void doFilter(ServletRequest request,
110: ServletResponse response, FilterChain filterChain)
111: throws IOException, ServletException {
112: if (!(request instanceof HttpServletRequest)) {
113: throw new ServletException(
114: "Can only process HttpServletRequest");
115: }
116:
117: if (!(response instanceof HttpServletResponse)) {
118: throw new ServletException(
119: "Can only process HttpServletResponse");
120: }
121:
122: HttpServletRequest httpRequest = (HttpServletRequest) request;
123: HttpServletResponse httpResponse = (HttpServletResponse) response;
124:
125: if (logger.isDebugEnabled()) {
126: logger.debug("Checking secure context token: "
127: + SecurityContextHolder.getContext()
128: .getAuthentication());
129: }
130:
131: if (SecurityContextHolder.getContext().getAuthentication() == null) {
132: Authentication authResult = null;
133: X509Certificate clientCertificate = extractClientCertificate(httpRequest);
134:
135: try {
136: X509AuthenticationToken authRequest = new X509AuthenticationToken(
137: clientCertificate);
138:
139: authRequest.setDetails(authenticationDetailsSource
140: .buildDetails((HttpServletRequest) request));
141: authResult = authenticationManager
142: .authenticate(authRequest);
143: successfulAuthentication(httpRequest, httpResponse,
144: authResult);
145: } catch (AuthenticationException failed) {
146: unsuccessfulAuthentication(httpRequest, httpResponse,
147: failed);
148: }
149: }
150:
151: filterChain.doFilter(request, response);
152: }
153:
154: private X509Certificate extractClientCertificate(
155: HttpServletRequest request) {
156: X509Certificate[] certs = (X509Certificate[]) request
157: .getAttribute("javax.servlet.request.X509Certificate");
158:
159: if ((certs != null) && (certs.length > 0)) {
160: return certs[0];
161: }
162:
163: if (logger.isDebugEnabled()) {
164: logger.debug("No client certificate found in request.");
165: }
166:
167: return null;
168: }
169:
170: public void init(FilterConfig ignored) throws ServletException {
171: }
172:
173: public void setApplicationEventPublisher(
174: ApplicationEventPublisher context) {
175: this .eventPublisher = context;
176: }
177:
178: public void setAuthenticationDetailsSource(
179: AuthenticationDetailsSource authenticationDetailsSource) {
180: Assert.notNull(authenticationDetailsSource,
181: "AuthenticationDetailsSource required");
182: this .authenticationDetailsSource = authenticationDetailsSource;
183: }
184:
185: public void setAuthenticationManager(
186: AuthenticationManager authenticationManager) {
187: this .authenticationManager = authenticationManager;
188: }
189:
190: /**
191: * Puts the <code>Authentication</code> instance returned by the authentication manager into the secure
192: * context.
193: *
194: * @param request DOCUMENT ME!
195: * @param response DOCUMENT ME!
196: * @param authResult DOCUMENT ME!
197: *
198: * @throws IOException DOCUMENT ME!
199: */
200: protected void successfulAuthentication(HttpServletRequest request,
201: HttpServletResponse response, Authentication authResult)
202: throws IOException {
203: if (logger.isDebugEnabled()) {
204: logger.debug("Authentication success: " + authResult);
205: }
206:
207: SecurityContextHolder.getContext()
208: .setAuthentication(authResult);
209:
210: // Fire event
211: if (this .eventPublisher != null) {
212: eventPublisher
213: .publishEvent(new InteractiveAuthenticationSuccessEvent(
214: authResult, this .getClass()));
215: }
216: }
217:
218: /**
219: * Ensures the authentication object in the secure context is set to null when authentication fails.
220: *
221: * @param request DOCUMENT ME!
222: * @param response DOCUMENT ME!
223: * @param failed DOCUMENT ME!
224: */
225: protected void unsuccessfulAuthentication(
226: HttpServletRequest request, HttpServletResponse response,
227: AuthenticationException failed) {
228: SecurityContextHolder.getContext().setAuthentication(null);
229:
230: if (logger.isDebugEnabled()) {
231: logger
232: .debug("Updated SecurityContextHolder to contain null Authentication");
233: }
234:
235: request
236: .getSession()
237: .setAttribute(
238: AbstractProcessingFilter.ACEGI_SECURITY_LAST_EXCEPTION_KEY,
239: failed);
240: }
241: }
|