使用 Spring 安全和 J2EE 容器身份验证记录访问被拒绝事件

log access denied events with Spring Security and J2EE container authentication

我已将 spring 安全配置为

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = false)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
        .authorizeRequests()
        .anyRequest().authenticated()
        .and()
        .jee()
        .mappableRoles("ROLE1", "ROLE2");
    }
}

然后 @Secured 在其余端点上带有角色的注释。

不管我做什么,我似乎无法为授权创建自定义处理程序(即用户成功登录但没有访问特定端点的正确角色)错误事件.

我试过的是:

  1. 具有 @ExceptionHandler(value = AccessDeniedException.class) 的异常处理程序 - 不会被调用。我知道这是设计使然,好的。

  2. AuthenticationEntryPoint 配置为 http.exceptionHandling().authenticationEntryPoint(new RestAuthenticationEntryPoint())

    @Component( "restAuthenticationEntryPoint" )
    public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
        @Override
        public void commence( HttpServletRequest request, HttpServletResponse response,
                              AuthenticationException authException ) throws IOException {
                              // logging
        }
    }
    

-没有被调用

  1. ApplicationListener - 我可以看到它在上下文关闭时被调用,因此它已正确注册但未在授权错误时被调用。

我只需要一个简单的处理程序来记录不成功的授权事件。

我完全忘记了 web.xml 中列出了允许的角色以及 j2ee 容器身份验证的工作。因此,任何不具备其中至少一种角色的用户都会被容器拒绝。

否则,第一种最简单的方法就可以了。希望我的错误对以后的人有所帮助