Extracted a method to evaluate the conditions for whether basic authentication is required.

This commit is contained in:
Luke Taylor 2007-02-23 19:21:44 +00:00
parent a1886bd1e0
commit bd2d4b013a

View File

@ -96,6 +96,7 @@ public class BasicProcessingFilter implements Filter, InitializingBean {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException { throws IOException, ServletException {
if (!(request instanceof HttpServletRequest)) { if (!(request instanceof HttpServletRequest)) {
throw new ServletException("Can only process HttpServletRequest"); throw new ServletException("Can only process HttpServletRequest");
} }
@ -126,15 +127,9 @@ public class BasicProcessingFilter implements Filter, InitializingBean {
password = token.substring(delim + 1); password = token.substring(delim + 1);
} }
// Only reauthenticate if username doesn't match SecurityContextHolder and user isn't authenticated (see SEC-53) if (authenticationIsRequired(username)) {
Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication(); UsernamePasswordAuthenticationToken authRequest =
new UsernamePasswordAuthenticationToken(username, password);
// Limit username comparison to providers which user usernames (ie UsernamePasswordAuthenticationToken) (see SEC-348)
if ((existingAuth == null)
|| (existingAuth instanceof UsernamePasswordAuthenticationToken && !existingAuth.getName().equals(username))
|| !existingAuth.isAuthenticated()) {
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username,
password);
authRequest.setDetails(authenticationDetailsSource.buildDetails((HttpServletRequest) request)); authRequest.setDetails(authenticationDetailsSource.buildDetails((HttpServletRequest) request));
Authentication authResult; Authentication authResult;
@ -178,6 +173,25 @@ public class BasicProcessingFilter implements Filter, InitializingBean {
chain.doFilter(request, response); chain.doFilter(request, response);
} }
private boolean authenticationIsRequired(String username) {
// Only reauthenticate if username doesn't match SecurityContextHolder and user isn't authenticated
// (see SEC-53)
Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
if(existingAuth == null || !existingAuth.isAuthenticated()) {
return true;
}
// Limit username comparison to providers which use usernames (ie UsernamePasswordAuthenticationToken)
// (see SEC-348)
if (existingAuth instanceof UsernamePasswordAuthenticationToken && !existingAuth.getName().equals(username)) {
return true;
}
return false;
}
public AuthenticationEntryPoint getAuthenticationEntryPoint() { public AuthenticationEntryPoint getAuthenticationEntryPoint() {
return authenticationEntryPoint; return authenticationEntryPoint;
} }