BasicProcessingFilter.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. /* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. package org.acegisecurity.ui.basicauth;
  16. import java.io.IOException;
  17. import javax.servlet.Filter;
  18. import javax.servlet.FilterChain;
  19. import javax.servlet.FilterConfig;
  20. import javax.servlet.ServletException;
  21. import javax.servlet.ServletRequest;
  22. import javax.servlet.ServletResponse;
  23. import javax.servlet.http.HttpServletRequest;
  24. import javax.servlet.http.HttpServletResponse;
  25. import org.acegisecurity.Authentication;
  26. import org.acegisecurity.AuthenticationException;
  27. import org.acegisecurity.AuthenticationManager;
  28. import org.acegisecurity.context.SecurityContextHolder;
  29. import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
  30. import org.acegisecurity.ui.AuthenticationDetailsSource;
  31. import org.acegisecurity.ui.AuthenticationDetailsSourceImpl;
  32. import org.acegisecurity.ui.AuthenticationEntryPoint;
  33. import org.acegisecurity.ui.rememberme.RememberMeServices;
  34. import org.apache.commons.codec.binary.Base64;
  35. import org.apache.commons.logging.Log;
  36. import org.apache.commons.logging.LogFactory;
  37. import org.springframework.beans.factory.InitializingBean;
  38. import org.springframework.core.Ordered;
  39. import org.springframework.util.Assert;
  40. /**
  41. * Processes a HTTP request's BASIC authorization headers, putting the result into the
  42. * <code>SecurityContextHolder</code>.<p>For a detailed background on what this filter is designed to process,
  43. * refer to <A HREF="http://www.faqs.org/rfcs/rfc1945.html">RFC 1945, Section 11.1</A>. Any realm name presented in
  44. * the HTTP request is ignored.</p>
  45. * <p>In summary, this filter is responsible for processing any request that has a HTTP request header of
  46. * <code>Authorization</code> with an authentication scheme of <code>Basic</code> and a Base64-encoded
  47. * <code>username:password</code> token. For example, to authenticate user "Aladdin" with password "open sesame" the
  48. * following header would be presented:</p>
  49. * <p><code>Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==</code>.</p>
  50. * <p>This filter can be used to provide BASIC authentication services to both remoting protocol clients (such as
  51. * Hessian and SOAP) as well as standard user agents (such as Internet Explorer and Netscape).</p>
  52. * <P>If authentication is successful, the resulting {@link Authentication} object will be placed into the
  53. * <code>SecurityContextHolder</code>.</p>
  54. * <p>If authentication fails and <code>ignoreFailure</code> is <code>false</code> (the default), an {@link
  55. * AuthenticationEntryPoint} implementation is called. Usually this should be {@link BasicProcessingFilterEntryPoint},
  56. * which will prompt the user to authenticate again via BASIC authentication.</p>
  57. * <p>Basic authentication is an attractive protocol because it is simple and widely deployed. However, it still
  58. * transmits a password in clear text and as such is undesirable in many situations. Digest authentication is also
  59. * provided by Acegi Security and should be used instead of Basic authentication wherever possible. See {@link
  60. * org.acegisecurity.ui.digestauth.DigestProcessingFilter}.</p>
  61. * <p>Note that if a {@link #rememberMeServices} is set, this filter will automatically send back remember-me
  62. * details to the client. Therefore, subsequent requests will not need to present a BASIC authentication header as
  63. * they will be authenticated using the remember-me mechanism.</p>
  64. * <p><b>Do not use this class directly.</b> Instead configure <code>web.xml</code> to use the {@link
  65. * org.acegisecurity.util.FilterToBeanProxy}.</p>
  66. *
  67. * @author Ben Alex
  68. * @version $Id: BasicProcessingFilter.java 1783 2007-02-23 19:21:44Z luke_t $
  69. */
  70. public class BasicProcessingFilter implements Filter, InitializingBean, Ordered {
  71. //~ Static fields/initializers =====================================================================================
  72. private static final Log logger = LogFactory.getLog(BasicProcessingFilter.class);
  73. //~ Instance fields ================================================================================================
  74. private AuthenticationDetailsSource authenticationDetailsSource = new AuthenticationDetailsSourceImpl();
  75. private AuthenticationEntryPoint authenticationEntryPoint;
  76. private AuthenticationManager authenticationManager;
  77. private RememberMeServices rememberMeServices;
  78. private boolean ignoreFailure = false;
  79. private int order;
  80. //~ Methods ========================================================================================================
  81. public void afterPropertiesSet() throws Exception {
  82. Assert.notNull(this.authenticationManager, "An AuthenticationManager is required");
  83. Assert.notNull(this.authenticationEntryPoint, "An AuthenticationEntryPoint is required");
  84. }
  85. public void destroy() {}
  86. public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
  87. throws IOException, ServletException {
  88. if (!(request instanceof HttpServletRequest)) {
  89. throw new ServletException("Can only process HttpServletRequest");
  90. }
  91. if (!(response instanceof HttpServletResponse)) {
  92. throw new ServletException("Can only process HttpServletResponse");
  93. }
  94. HttpServletRequest httpRequest = (HttpServletRequest) request;
  95. HttpServletResponse httpResponse = (HttpServletResponse) response;
  96. String header = httpRequest.getHeader("Authorization");
  97. if (logger.isDebugEnabled()) {
  98. logger.debug("Authorization header: " + header);
  99. }
  100. if ((header != null) && header.startsWith("Basic ")) {
  101. String base64Token = header.substring(6);
  102. String token = new String(Base64.decodeBase64(base64Token.getBytes()));
  103. String username = "";
  104. String password = "";
  105. int delim = token.indexOf(":");
  106. if (delim != -1) {
  107. username = token.substring(0, delim);
  108. password = token.substring(delim + 1);
  109. }
  110. if (authenticationIsRequired(username)) {
  111. UsernamePasswordAuthenticationToken authRequest =
  112. new UsernamePasswordAuthenticationToken(username, password);
  113. authRequest.setDetails(authenticationDetailsSource.buildDetails((HttpServletRequest) request));
  114. Authentication authResult;
  115. try {
  116. authResult = authenticationManager.authenticate(authRequest);
  117. } catch (AuthenticationException failed) {
  118. // Authentication failed
  119. if (logger.isDebugEnabled()) {
  120. logger.debug("Authentication request for user: " + username + " failed: " + failed.toString());
  121. }
  122. SecurityContextHolder.getContext().setAuthentication(null);
  123. if (rememberMeServices != null) {
  124. rememberMeServices.loginFail(httpRequest, httpResponse);
  125. }
  126. if (ignoreFailure) {
  127. chain.doFilter(request, response);
  128. } else {
  129. authenticationEntryPoint.commence(request, response, failed);
  130. }
  131. return;
  132. }
  133. // Authentication success
  134. if (logger.isDebugEnabled()) {
  135. logger.debug("Authentication success: " + authResult.toString());
  136. }
  137. SecurityContextHolder.getContext().setAuthentication(authResult);
  138. if (rememberMeServices != null) {
  139. rememberMeServices.loginSuccess(httpRequest, httpResponse, authResult);
  140. }
  141. }
  142. }
  143. chain.doFilter(request, response);
  144. }
  145. private boolean authenticationIsRequired(String username) {
  146. // Only reauthenticate if username doesn't match SecurityContextHolder and user isn't authenticated
  147. // (see SEC-53)
  148. Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
  149. if(existingAuth == null || !existingAuth.isAuthenticated()) {
  150. return true;
  151. }
  152. // Limit username comparison to providers which use usernames (ie UsernamePasswordAuthenticationToken)
  153. // (see SEC-348)
  154. if (existingAuth instanceof UsernamePasswordAuthenticationToken && !existingAuth.getName().equals(username)) {
  155. return true;
  156. }
  157. return false;
  158. }
  159. public AuthenticationEntryPoint getAuthenticationEntryPoint() {
  160. return authenticationEntryPoint;
  161. }
  162. public AuthenticationManager getAuthenticationManager() {
  163. return authenticationManager;
  164. }
  165. public void init(FilterConfig arg0) throws ServletException {}
  166. public boolean isIgnoreFailure() {
  167. return ignoreFailure;
  168. }
  169. public void setAuthenticationDetailsSource(AuthenticationDetailsSource authenticationDetailsSource) {
  170. Assert.notNull(authenticationDetailsSource, "AuthenticationDetailsSource required");
  171. this.authenticationDetailsSource = authenticationDetailsSource;
  172. }
  173. public void setAuthenticationEntryPoint(AuthenticationEntryPoint authenticationEntryPoint) {
  174. this.authenticationEntryPoint = authenticationEntryPoint;
  175. }
  176. public void setAuthenticationManager(AuthenticationManager authenticationManager) {
  177. this.authenticationManager = authenticationManager;
  178. }
  179. public void setIgnoreFailure(boolean ignoreFailure) {
  180. this.ignoreFailure = ignoreFailure;
  181. }
  182. public void setRememberMeServices(RememberMeServices rememberMeServices) {
  183. this.rememberMeServices = rememberMeServices;
  184. }
  185. public int getOrder() {
  186. return order;
  187. }
  188. public void setOrder(int order) {
  189. this.order = order;
  190. }
  191. }