[英]Spring Boot: accessDeniedHandler does not work
我有以下 Spring Security 配置:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/api/private/**", "/app/**").authenticated();
http.csrf().disable();
http.logout().logoutSuccessUrl("/");
http.exceptionHandling().accessDeniedPage("/403"); //.accessDeniedHandler(accessDeniedHandler);
}
}
我期望以下邏輯:未通過身份驗證的用戶將被重定向到/403
。 而不是 Spring 顯示默認的 Tomcat 403 頁面。 我也嘗試過自定義accessDeniedHandler
但沒有成功。
如何在訪問失敗時實現自定義邏輯?
AccessDeniedHandler 僅適用於經過身份驗證的用戶。 未經身份驗證的用戶的默認行為是重定向到登錄頁面(或任何適用於正在使用的身份驗證機制的頁面)。
如果你想改變你需要配置一個AuthenticationEntryPoint
,當未經AuthenticationEntryPoint
驗證的用戶嘗試訪問受保護的資源時調用它。 你應該可以使用
http.exceptionHandling().authenticationEntryPoint(...)
而不是你所擁有的。 有關更多詳細信息,請查看API 文檔。
遇到這個問題,它幫助我解決了我的問題,下面是我的代碼:
public class CustomHttp403ForbiddenEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
response.getWriter().print("You need to login first in order to perform this action.");
}
}
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException arg2)
throws IOException, ServletException {
response.getWriter().print("You don't have required role to perform this action.");
}
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.exceptionHandling().accessDeniedHandler(new CustomAccessDeniedHandler()).and()
.exceptionHandling().authenticationEntryPoint(new CustomHttp403ForbiddenEntryPoint());
}
希望這可以幫助。
正常的 Spring Security 行為是將未經身份驗證的用戶重定向到您的登錄頁面,如下所示。 驗證未經授權(沒有 ADMIN 角色)的用戶將被定向到訪問被拒絕頁面:
http.authorizeRequests().antMatchers("/admin/**")
.access("hasRole('ADMIN')")
.and().formLogin().loginPage("/login")
.and().exceptionHandling().accessDeniedPage("/403");
如果您已經實現了自己的身份驗證機制,並且不指望 Spring Security 配置將未經身份驗證的用戶傳送到您的登錄頁面,則可以按如下方式使用 Spring Security 配置 - 為您的自定義 403 頁面提供服務,而不是真正的登錄頁面:
http.authorizeRequests().antMatchers("/admin/**")
.access("hasRole('ADMIN')")
.and().formLogin().loginPage("/403")
.and().exceptionHandling().accessDeniedPage("/403");
用這個:-
@Configuration
public class ViewRegistryConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/403").setViewName("notAuth");
}
}
並在您的模板文件夾中創建 notAuth.html 頁面
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.