5

我正在使用 Spring Security 3.1 对网站的用户进行身份验证。当由于 Spring Security 无法连接到数据库而导致登录失败时,我的日志中会出现以下语句:

2012-07-12 11:42:45,419 [ajp-bio-8009-exec-1] DEBUG      org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter - Authentication request failed: org.springframework.security.authentication.AuthenticationServiceException: Could not get JDBC Connection; nested exception is java.sql.SQLException: Connections could not be acquired from the underlying database!

我的问题是,为什么这是 DEBUG 语句而不是 ERROR?为了找到实际的错误,我必须翻阅大量的调试语句。

编辑

这是我的身份验证管理器:

<bean id="securityDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:comp/env/securityDS"/>
    <property name="resourceRef" value="true"/>
</bean>

<bean id="encoder" class="org.springframework.security.crypto.password.StandardPasswordEncoder" />

<security:authentication-manager>
    <security:authentication-provider>
        <security:password-encoder ref="encoder" />
        <security:jdbc-user-service 
            data-source-ref="securityDataSource"
            authorities-by-username-query="SELECT username, authority FROM login WHERE username = ?"
            users-by-username-query="SELECT username, password, enabled FROM login WHERE username = ?"
        />        
    </security:authentication-provider>
</security:authentication-manager>
4

2 回答 2

17

我的解决方案:

@Component
public class AuthenticationEventListener implements ApplicationListener<AbstractAuthenticationEvent> {

   private static Logger logger = Logger.getLogger(AuthenticationEventListener.class);

   @Override
   public void onApplicationEvent(AbstractAuthenticationEvent authenticationEvent) {
      if (authenticationEvent instanceof InteractiveAuthenticationSuccessEvent) {
         // ignores to prevent duplicate logging with AuthenticationSuccessEvent
         return;
      }
      Authentication authentication = authenticationEvent.getAuthentication();
      String auditMessage = "Login attempt with username: " + authentication.getName() + "\t\tSuccess: " + authentication.isAuthenticated();
      logger.info(auditMessage);
   }

}

不需要其他配置。

于 2013-07-17T10:00:32.107 回答
8

该消息打印在AbstractAuthenticationProcessingFilter.unsuccessfulAuthentication

protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException failed) throws IOException, ServletException {
    SecurityContextHolder.clearContext();

    if (logger.isDebugEnabled()) {
        logger.debug("Authentication request failed: " + failed.toString());

身份验证失败的方式有很多种,包括基于用户输入。例如,在 中AbstractUserDetailsAuthenticationProvider.authenticateBadCredentialsException如果未找到用户名,则可能会抛出 a:

        try {
            user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication);
        } catch (UsernameNotFoundException notFound) {
            logger.debug("User '" + username + "' not found");

            if (hideUserNotFoundExceptions) {
                throw new BadCredentialsException(messages.getMessage(
                        "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
            } else {
                throw notFound;
            }
        }

AbstractAuthenticationProcessingFilter由于身份验证失败可能有合理的原因,因此记录错误是没有意义的。如果存在系统错误,则应该在下游记录该错误。

我怀疑问题出在DaoAuthenticationProvider(请参阅我的内联评论):

protected final UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
        throws AuthenticationException {
    UserDetails loadedUser;

    try {
        loadedUser = this.getUserDetailsService().loadUserByUsername(username);
    }
    catch (DataAccessException repositoryProblem) {
        // *** ERROR SHOULD BE LOGGED HERE ***
        throw new AuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);
    }

也许应该在这里记录一个错误——你可以用 Spring 记录一个 JIRA 来请求它。尽管他们可能假设每个人都将提供自定义UserDetailsService并会在那里捕获/记录他们自己的异常。如果你正在使用JdbcDaoImpl它不会。我认为JdbcDaoImpl旨在作为一个例子,并不强大。根据文档:

好消息是我们提供了许多 UserDetailsS​​ervice 实现,包括一个使用内存映射 (InMemoryDaoImpl) 和另一个使用 JDBC (JdbcDaoImpl)。然而,大多数用户倾向于编写自己的实现,他们的实现通常只是位于代表其员工、客户或应用程序其他用户的现有数据访问对象 (DAO) 之上。

于 2012-07-13T00:54:22.550 回答