java - 如果授权失败,Spring Controller 上的 @PreAuthorize 会发送重定向

标签 java spring-mvc spring-security

我已经让 spring security 成功评估了我的 Controller 上的 @PreAuthorize。如果我使用“permitAll”,那么我可以查看该页面,如果我使用“isAuthenticated()”,那么我会得到一个丑陋的“访问被拒绝”堆栈跟踪。如果我将配置放在安全上下文配置 xml 文件中 http 节点内的拦截 URL 中,那么我会很好地重定向到登录页面,而不是在页面中获取令人讨厌的堆栈跟踪。

有没有办法让我只使用注释机制来获得重定向?

最佳答案

我让这个工作了。我必须处理一些事情。

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

安全上下文.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>

请注意,loginUrlAuthenticationEntryPoint 实际上不是解决方案的一部分,它是访问拒绝处理程序。

我的 mvc-config.xml 仍然具有 SimpleMappingExceptionResolver,但没有配置 defaultErrorView。如果我继续走这条路,我可能会实现自己的 SimpleMappingExceptionResolver,让身份验证和授权异常(exception)通过,或者在 SimpleMappingExceptionResolver 中配置它。

这笔交易的 killer 锏是我还没有找到通过注释从拦截url配置requires-channel="https"的方法,所以我现在将它放在xml配置文件中无论如何。

关于java - 如果授权失败,Spring Controller 上的 @PreAuthorize 会发送重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4150300/

相关文章:

java - Spring Boot Security - Postman 给出 401 Unauthorized

java - 在循环中添加作业但在 JAVA 中花费额外 50% 的时间

java - Vaadin 和 jInstagram 不支持major.minor 版本51.0

java - Java GUI 中的文档模型

java - 没有 Hibernate session 绑定(bind)到带有 generic-hibernate-dao 库的线程

Spring 安全注释不适用于服务层

java - Java中的抽象方法

java - 我的 spring MVC 中的错误

java - 具有 Spring session 和安全性的 Spring Boot。 RMI 失败并返回 401

java - 如何使用 oAuth2/spring security 限制一个连接/用户