我的 spring 安全配置:
<security:http auto-config="true" use-expressions="true" >
<security:intercept-url pattern="/game/**" access="isAuthenticated()"/>
<security:intercept-url pattern="/**" access="permitAll"/>
<security:form-login password-parameter="password" username-parameter="username" login-page="/"
default-target-url="/game/" login-processing-url="/processLogin" authentication-failure-url="/"/>
<security:logout logout-url="/game/logout" logout-success-url="/" delete-cookies="true" invalidate-session="true"/>
<security:access-denied-handler ref="accessDeniedHandler" />
</security:http>
自定义处理器:
@Component
public class AccessDeniedHandler extends AccessDeniedHandlerImpl {
@Override
public void handle(HttpServletRequest request,
HttpServletResponse response, AccessDeniedException exception)
throws IOException, ServletException {
super.handle(request, response, exception);
}
}
异常解析器:
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key=".AccessDeniedException">accessDenied</prop>
</props>
</property>
</bean>
我遇到的问题是 spring security 不会抛出任何异常。例如,当我输入一个 protected url 时,它会将我重定向到登录页面。如果我从配置中删除登录页面,它会将我重定向到 spring security 默认登录表单。因此,我无法处理任何异常,例如 AccessDeniedException。正如您在上面看到的,我已经定义了自定义访问被拒绝的处理程序,它覆盖了 handle 方法,但它甚至没有进入其中。我也尝试过使用 SimpleMappingExceptionResolver 但这也不起作用。 所以我的问题是:如何让 spring security 抛出异常,以便我可以通过解析器或自定义处理程序捕获它们?
最佳答案
我的 AccessDeniedHandler 不起作用的原因是因为它只适用于经过身份验证的用户,所以为了在未经身份验证的用户尝试访问仅供经过身份验证的用户访问的内容时显示错误页面(这是试图捕获一个AccessDeniedException),您应该编写您的自定义入口点,并覆盖默认入口点。
感谢 Luke Taylor 向我澄清了这一点。
关于java - Spring Security 不会抛出任何异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26590669/