Spring Boot:accessDeniedHandler不起作用

fed*_*lov 13 java spring spring-security spring-boot

我有以下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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我期望以下逻辑:未经过身份验证的用户将被重定向到/403.而不是Spring显示默认的Tomcat 403页面.我也尝试过定制,accessDeniedHandler但没有任何成功.

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

Sha*_*eep 28

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

如果要更改,则需要配置AuthenticationEntryPoint一个未经身份验证的用户尝试访问受保护资源时调用的内容.你应该可以使用

http.exceptionHandling().authenticationEntryPoint(...)
Run Code Online (Sandbox Code Playgroud)

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

  • 救星“AccessDeniedHandler 仅适用于经过身份验证的用户” (2认同)

GMs*_*soF 9

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

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.");
    }

}
Run Code Online (Sandbox Code Playgroud)
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.");
    }

}
Run Code Online (Sandbox Code Playgroud)
@Override
protected void configure(HttpSecurity http) throws Exception {

    http.exceptionHandling().accessDeniedHandler(new CustomAccessDeniedHandler()).and()
        .exceptionHandling().authenticationEntryPoint(new CustomHttp403ForbiddenEntryPoint());
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。