Servlet principal in high precedence filter, using Spring Security

时间:2016-05-17 15:16:12

标签: spring servlets spring-security spring-boot servlet-filters

Our Spring Boot 1.3.3 application uses Spring Security. We need to log HTTP requests including requested URL, HTTP verb, processing time, user principal.

This is done using a custom servlet filter.

The custom filter must have higher precedence (i.e. smaller order) than Spring Security filter chain, or else it won't be executed for requests rejected by Spring Security.

But then in the custom filter, HttpServletRequest:getUserPrincipal is always null. It seems that Spring Security removes security information once his security chain is done.

Is there a standard way (meaning without thread local magic) to always get the user principal from a custom filter when using Spring Security?

Thank you for your time.

1 个答案:

答案 0 :(得分:1)

当您使用Spring Security时,可能会由Spring Security机制精确设置主体。但更糟糕的是,它使用了请求包装,因此在调用FilterChain之前你不会找到它,因为它尚未设置,也不会因为它是在不再存在的HttpServletRequestWrapper中设置的。

所以恕我直言,你最好的选择是在Spring安全链中放置一个自定义过滤器,就在ExceptionTranslationFilter之前,在链接后记录并传递任何异常。