@PreAuthorize弹簧控制器在授权失败时发送重定向

dig*_*oel 2 java spring-mvc spring-security

我有Spring安全性成功评估了我的控制器上的@PreAuthorize.如果我使用"permitAll"然后我可以查看页面,如果我使用"isAuthenticated()",那么我得到一个丑陋的访问被拒绝的堆栈跟踪.如果我将配置放在我的安全上下文配置xml文件中的http节点内的intercept-url中,那么我很好地重定向到登录页面,而不是在我的页面中获得令人讨厌的堆栈跟踪.

有没有办法让我只使用注释机制进行重定向?

dig*_*oel 5

我得到了这个工作.有几件事我不得不处理.

首先,我的Spring MVC配置有一个SimpleMappingExceptionResolver,配置了defaultErrorView.那是在他们到达我在安全配置中的http元素中配置的访问被拒绝处理程序之前拦截了身份验证和授权错误.最终的代码看起来像这样.

securitycontext.xml

<global-method-security pre-post-annotations="enabled"/>

<!-- HTTP security configurations -->
<http auto-config="false" use-expressions="true" entry-point-ref="loginUrlAuthenticationEntryPoint">
    <access-denied-handler ref="myAccessDeniedHandler" />
    ... other configuration here ...
</http>

<!-- handler for authorization failure.  Will redirect to the login page. -->
<beans:bean id="myAccessDeniedHandler" class="org.springframework.security.web.access.AccessDeniedHandlerImpl">
    <beans:property name="errorPage" value="/index" />
</beans:bean>
Run Code Online (Sandbox Code Playgroud)

请注意,loginUrlAuthenticationEntryPoint实际上不是解决方案的一部分,它是access-denied-handler.

我的mvc-config.xml仍然具有SimpleMappingExceptionResolver,但没有配置defaultErrorView.如果我继续这个路径,我可能会实现我自己的SimpleMappingExceptionResolver,它将允许身份验证和授权激活,或者在SimpleMappingExceptionResolver中配置它.

这笔交易的杀手是我没有找到通过注释从intercept-url配置requires-channel ="https"的方法,所以无论如何我现在都会把它放在xml配置文件中.