簡體   English   中英

@PreAuthorize彈簧控制器在授權失敗時發送重定向

[英]@PreAuthorize on spring controller sending redirect if authorization fails

我有Spring安全性成功評估了我的控制器上的@PreAuthorize。 如果我使用“permitAll”然后我可以查看頁面,如果我使用“isAuthenticated()”,那么我得到一個丑陋的訪問被拒絕的堆棧跟蹤。 如果我將配置放在我的安全上下文配置xml文件中的http節點內的intercept-url中,那么我很好地重定向到登錄頁面,而不是在我的頁面中獲得令人討厭的堆棧跟蹤。

有沒有辦法讓我只使用注釋機制進行重定向?

我得到了這個工作。 有幾件事我不得不處理。

首先,我的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>

請注意,loginUrlAuthenticationEntryPoint實際上不是解決方案的一部分,它是access-denied-handler。

我的mvc-config.xml仍然具有SimpleMappingExceptionResolver,但沒有配置defaultErrorView。 如果我繼續這個路徑,我可能會實現我自己的SimpleMappingExceptionResolver,它將允許身份驗證和授權激活,或者在SimpleMappingExceptionResolver中配置它。

這筆交易的殺手是我沒有找到一種方法來通過注釋從intercept-url配置requires-channel =“https”,所以我現在無論如何都要把它放在xml配置文件中。

您可以通過覆蓋安全性入口點來自定義錯誤處理。 篩選鏈中發生的所有異常(由您在web.xml文件中定義的映射定義)都會被捕獲並可在此處理。 如果沒有處理它們,那么ExceptionTranslationFilter將接管。

您可以像這樣定義自己的入口點:

public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, org.springframework.security.core.AuthenticationException authException) throws IOException, ServletException {

        if (authException != null) {
            // you can check for the spefic exception here and redirect like this
            response.sendRedirect("403.html");
        }
    }
}

您可以將此設置為xml配置文件中的入口點,將其指定為入口點:

<http entry-point-ref="customAuthenticationEntryPoint">

  ...

</http>

在您的特定情況下,PreInvocationAuthorizationAdviceVoter將由您在配置中指定的任何AccessDecisionManager調用(通常是以下之一:AffirmativeBased,ConsensusBased或UnanimousBased)。 您將看到這些Voters拋出了AccessDeniedException,您可以在入口點專門捕獲和處理它。

格蘭特

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM