Spring Security – 自定義 403 禁止/訪問拒絕頁面

Spring Security
Remote
0
12:50 AM · Nov 30 ,2025

1. 簡介在本文中,我們將展示如何自定義 Spring Security 項目中的“訪問拒絕”頁面。

這可以通過 Spring Security 配置或在 web.xml 文件中的 Web 應用程序配置來實現。

在接下來的部分中,我們將更深入地研究這些選項。

2. 自定義 JSP

當用户嘗試訪問其未具有的權限的角色限制的頁面時,應用程序將返回狀態碼 403,這意味着 訪問被拒絕

為了將 Spring 403 狀態響應頁面替換為自定義頁面,讓我們首先創建一個名為 accessDenied.jspJSP 文件:


    

抱歉,您沒有權限查看此頁面。

">這裏 前往主頁。

3. Spring Security Configuration

By default, Spring Security has an ExceptionTranslationFilter defined which handles exceptions of type AuthenticationException and AccessDeniedException. The latter is done through a property called accessDeniedHandler, which uses the AccessDeniedHandlerImpl class.

In order to customize this behavior to use our own page that we created above, we need to override the properties of the ExceptionTranslationFilter class. This can be done through either Java configuration or XML configuration.

3.1. Access Denied Page

Using Java, we can customize the 403 error handling process by using theaccessDeniedPage() or accessDeniedHandler() methods while configuring the HttpSecurity element.

Let’s create an authentication configuration that restricts the “/admin/**” URLs to the ADMIN role and sets the access denied page to our custom accessDenied.jsp page:

@Override
protected void configure(final HttpSecurity http) throws Exception {
    http
      // ...
      .and()
      .exceptionHandling().accessDeniedPage("/accessDenied.jsp");
}

Let’s take a look at the equivalent XML configuration for the access denied page:

<http use-expressions="true">
    <access-denied-handler error-page="/accessDenied"/>
 </http>

3.2. Access Denied Handler

Using an access denied handler instead of a page has the advantage that we can define custom logic to be executed before redirecting to the 403 page. For this, we need to create a class that implements the AccessDeniedHandler interface and overrides the handle() method.

Let’s create a custom AccessDeniedHandler class that logs a warning message for every access denied attempt containing the user that made the attempt and the protected URL they were trying to access:

public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    public static final Logger LOG
      = Logger.getLogger(CustomAccessDeniedHandler.class);

    @Override
    public void handle(
      HttpServletRequest request,
      HttpServletResponse response, 
      AccessDeniedException exc) throws IOException, ServletException {
        
        Authentication auth 
          = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null) {
            LOG.warn("User: " + auth.getName() 
              + " attempted to access the protected URL: "
              + request.getRequestURI());
        }

        response.sendRedirect(request.getContextPath() + "/accessDenied");
    }
}

In the security configuration, we’ll define the bean and set the custom AccessDeniedHandler:

@Bean
public AccessDeniedHandler accessDeniedHandler(){
    return new CustomAccessDeniedHandler();
}

//...
.exceptionHandling().accessDeniedHandler(accessDeniedHandler());

If we want to configure the CustomAccessDeniedHandler class defined above using XML, the configuration will look slightly different:

<bean name="customAccessDeniedHandler" 
  class="com.baeldung.security.CustomAccessDeniedHandler" />

<http use-expressions="true">
    <access-denied-handler ref="customAccessDeniedHandler"/>
</http>

4. 應用配置

通過 Web 應用的 web.xml文件處理訪問拒絕錯誤,可以通過定義 error-page標籤來實現。該標籤包含兩個子標籤,error-code,指定要攔截的狀態碼,以及 location,表示在遇到錯誤碼時,用户將被重定向到的 URL:

<error-page>
    <error-code>403</error-code>
    <location>/accessDenied</location>
</error-page>

如果應用程序沒有 web.xml文件,如 Spring Boot 的情況,Spring 註解目前尚不能提供與 error-page標籤完全等效的替代方案。根據 Spring 文檔,在這種情況下,推薦的方法是使用方法 accessDeniedPage()accessDeniedHandler(),這些方法在第 3 節中介紹。

5. 結論

在本文中,我們詳細介紹瞭如何使用自定義 403 頁來處理訪問權限被拒絕錯誤。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.