弹簧靴:访问DeniedHandler不起作用

2022-09-02 22:59:14

我有以下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);
    }
}

我期望以下逻辑:未经身份验证的用户将被重定向到。而不是那个 Spring 显示默认的 Tomcat 403 页面。我也尝试过定制,尽管取得了任何成功。/403accessDeniedHandler

如何在访问失败时实现自定义逻辑?


答案 1

AccessDeniedHandler 仅适用于经过身份验证的用户。未经身份验证的用户的默认行为是重定向到登录页面(或适用于正在使用的身份验证机制的任何页面)。

如果要更改,则需要配置 ,当未经身份验证的用户尝试访问受保护的资源时,将调用该操作。您应该能够使用AuthenticationEntryPoint

http.exceptionHandling().authenticationEntryPoint(...)

而不是你所拥有的。有关更多详细信息,请查看 API 文档


答案 2

遇到这个问题,它帮助我解决了我的问题,下面是我的代码:

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());
}

希望这有帮助。


推荐