You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Grails 2.2.3中开启Spring Security日志功能?

Spring Security 自定义onAuthenticationFailure未输出完整日志问题处理

你当前自定义的onAuthenticationFailure方法没有输出完整认证失败日志,核心原因是代码里缺少显式的日志记录逻辑:

  • saveException(request, exception)仅将异常存储到Session中,不会输出到日志系统
  • 调用super.onAuthenticationFailure只会处理默认的跳转逻辑,也不会打印异常的完整堆栈信息

要实现完整日志输出,直接在方法中添加日志记录即可,以下是修改后的代码示例:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// 其他必要导入...

public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    private static final Logger logger = LoggerFactory.getLogger(CustomAuthenticationFailureHandler.class);
    private String _ajaxAuthenticationFailureUrl;

    @Override
    public void onAuthenticationFailure(final HttpServletRequest request, final HttpServletResponse response,
                                        final AuthenticationException exception) throws IOException, ServletException {
        // 记录完整的认证失败日志(包含堆栈信息)
        logger.error("用户认证失败,请求地址:{}", request.getRequestURI(), exception);

        ObjectMapper objectMapper = new ObjectMapper();

        if (SpringSecurityUtils.isAjax(request)) {
            saveException(request, exception);
            getRedirectStrategy().sendRedirect(request, response, _ajaxAuthenticationFailureUrl);
        } else {
            super.onAuthenticationFailure(request, response, exception);
        }
    }

    // 此处可添加_ajaxAuthenticationFailureUrl的setter方法
}

关键说明:

  • 使用SLF4J日志框架(Spring生态默认集成),通过logger.error方法传入exception参数,会自动打印完整的堆栈跟踪信息
  • 确保项目的日志配置(如logback.xml、log4j2.xml)中,将当前Handler类或Spring Security相关包的日志级别设置为ERROR或DEBUG,保证日志能正常输出

内容的提问来源于stack exchange,提问作者Mohammad Reza Eshraghian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 10:00:01