【问题标题】:Spring Security AccessDeniedException caught by @ExceptionHandler@ExceptionHandler 捕获的 Spring Security AccessDeniedException
【发布时间】:2014-02-03 17:14:52
【问题描述】:

我有以下 spring-security.xml

<security:global-method-security proxy-target-class="true" secured-annotations="enabled" />
<security:http auto-config="false" use-expressions="true" entry-point-ref="customLoginEndpoint" >
    <security:custom-filter ref="authenticationFilter" position="FORM_LOGIN_FILTER"/>
</security:http>

<bean id="authenticationFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter"
    p:authenticationManager-ref="customAuthenticationManager"/>

下面是customLoginEndpoint

@Component("customLoginEndpoint")
public class CustomLoginEndpoint extends LoginUrlAuthenticationEntryPoint
{
    public AcapLoginEndpoint()
    {
        super("/auth/login");
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) 
            throws IOException, ServletException {
        response.sendRedirect("/auth/login");
    }   
}

我的控制器类有一个 @ExceptionHandler(Throwable ex) 和几个有 @Secured 注解的方法

问题是@ExceptionHandler 方法捕获了所有由@Secured 注释引起的org.springframework.security.access.AccessDeniedException,因此请求永远不会到达CustomLoginEndpoint.commence 并被拒绝。

如果我删除 @ExceptionHandler 那么一切正常。

我如何让这个工作开始被调用并避免@ExceptionHandler 捕获由于@Secured 注释而导致的 AccessDeniedException。

【问题讨论】:

    标签: spring-security


    【解决方案1】:

    您应该能够为 AccessDeniedException 添加另一个 @ExceptionHandler,然后简单地在 handle 方法中重新抛出异常。这将允许 AccessDeniedException 向上传播,以便 Spring Security 可以处理错误。

    【讨论】:

    • 太好了,有用吗?但是这种解决方案有副作用吗?
    • 我能想到的唯一缺点是捕获和重新抛出异常的开销可能非常小
    • 作为副作用,您将收到“失败”处理程序方法(重新抛出 AccessDeniedException)的级别 ERROR 的日志消息,如果没有“catch-the-”,您将无法获得世界”@ExceptionHandler
    • @Holgzn 在 Spring Boot、Security OAuth2 资源服务器中遇到了完全相同的问题,工作完美,没有额外的日志消息。
    猜你喜欢
    • 2013-01-03
    • 2017-06-14
    • 2013-04-10
    • 1970-01-01
    • 2013-07-05
    • 1970-01-01
    • 2017-12-30
    • 2016-08-15
    • 2012-10-26
    相关资源
    最近更新 更多