繁体   English   中英

Spring FilterChain + Security:用户是否记录日志请求

[英]Spring FilterChain + Security: log request with user or not

我有一个带有几个初始化程序的Spring web-mvc REST服务。

WebAppInitializer.java

@Order(1)
public class MyFiltersInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) {
        FilterRegistration.Dynamic registration = servletContext.addFilter("myRequestFilter", DelegatingFilterProxy.class);
        // register other filters and DispatcherServlet
    }
}

SecurityWebAppInitializer.java

@Order(2)
public class MySecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {

    @Override
    protected Set<SessionTrackingMode> getSessionTrackingModes() {
        return EnumSet.of(SessionTrackingMode.COOKIE, SessionTrackingMode.URL);
    }
}

如您所见,在所有自定义请求筛选器之后添加了SecurityFilterChain 我需要做的是记录每个请求,并包括User记录,如果请求被授权

MyRequestFilter.java这样的东西:

@Slf4j
public class RequestFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(final HttpServletRequest request,
                                    final HttpServletResponse response,
                                    final FilterChain filterChain) throws ServletException, IOException {
           MyUser user = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); //no auth yet
           log.debug("request {} start, user {}", request, user); 
           filterChain.doFilter(request, response); //may return 401 or 403, what also need to be logged
           log.debug("request {} end with response {}", request, response);
   }

有一个想法是添加一个LogBodyHolder ,它保持日志体直到完全传递SecurityChain ,然后调用log.debug 但有解决这个问题的任何漂亮的方式?

你可以创建一个扩展类的Spring bean AbstractRequestLoggingFilter这是由Spring提供,然后覆盖beforeRequest()afterRequest()方法,你想添加你的日志。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM