有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spring@ExceptionHandler未捕获AccessDeniedException

我用以下代码设置了一个异常处理程序

@ExceptionHandler(Throwable.class)
public @ResponseBody CustomResponse handleException(Throwable throwable){
    // handles exception, returns a JSON
}

我使用的是SpringSecurity 3.1。当我尝试在没有身份验证的情况下执行操作时,应用程序抛出AccessDeniedException。这种方法永远不会出现。但在其他例外情况下效果良好。这就是它的工作方式吗??还是我的代码有问题

This看起来是个解决方案。但如果我能在一个点上处理异常,那就更好了

这是我的配置文件

<global-method-security secured-annotations="enabled" pre-post-annotations="enabled" />
<http auto-config="true" use-expressions="true">
    //intercept urls
    <form-login login-page="/signin" default-target-url="/" always-use-default-target="true"/>
</http>

<authentication-manager>
    <authentication-provider user-service-ref="userDetailsService">
        <password-encoder ref="encoder" />
    </authentication-provider>
</authentication-manager>

<!-- This encoder doesn't require a salt -->
<beans:bean id="encoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />

更新

此处用户未经过身份验证(角色\匿名)。当我尝试访问受保护的页面时,它会将我重定向到登录URL。我这里的问题是,我进行了一个AJAX调用。因此,重定向到返回ModelAndView的方法不起作用。这附近有工作吗


共 (2) 个答案

  1. # 1 楼答案

    我猜您在spring安全配置中定义了^{}。此处理程序正在捕获AccessDeniedException。 这可能就是为什么你不能在你的泛型ExceptionHandler中找到它

    有一个默认的AccessDeniedHandler(附带默认的spring安全设置)。请阅读this了解更多详细信息

  2. # 2 楼答案

    Spring Security的请求处理都是在调用dispatcher servlet之前在过滤器链中进行的,因此它对Spring MVC异常处理程序一无所知,事实上,它完全可以在没有Spring MVC的情况下使用

    您看到的是未经身份验证的用户的expected behaviour,但您不希望Ajax调用被重定向到UI代码。很难说最好的解决方案是什么,因为对于未经验证的ajax调用,您想要的行为并不明显。例如,如果希望它们在403中失败,那么可以将ajax api分离到单独的过滤器链中。例如,如果您的ajax调用是对/ajaxapi,则可以在现有链定义之前添加以下链定义:

    <http pattern="/ajaxapi/**" create-session="never" use-expressions="true" entry-point-ref="entryPoint">
        <intercept-url pattern="/**" access="isAuthenticated()" />
    </http>
    
    <bean entryPoint="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint" />
    

    ajax调用将得到403响应,直到用户通过浏览器界面进行身份验证