1. 簡介
在本文中,我們將展示如何自定義 Spring Security 項目中的“訪問拒絕”頁面。這可以通過 Spring Security 配置或在 web.xml 文件中的 Web 應用程序配置來實現。
在接下來的部分中,我們將更深入地研究這些選項。
2. 自定義 JSP
當用户嘗試訪問其未具有的權限的角色限制的頁面時,應用程序將返回狀態碼 403,這意味着 訪問被拒絕。
為了將 Spring 403 狀態響應頁面替換為自定義頁面,讓我們首先創建一個名為 accessDenied.jsp 的 JSP 文件:
抱歉,您沒有權限查看此頁面。
">這裏
前往主頁。
3. Spring Security Configuration
By default, Spring Security has an
In order to customize this behavior to use our own page that we created above, we need to override the properties of the
3.1. Access Denied Page
Using Java,
Let’s create an authentication configuration that restricts the
@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,
Let’s create a custom
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,
@Bean
public AccessDeniedHandler accessDeniedHandler(){
return new CustomAccessDeniedHandler();
}
//...
.exceptionHandling().accessDeniedHandler(accessDeniedHandler());
If we want to configure the
<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 頁來處理訪問權限被拒絕錯誤。