繁体   English   中英

Spring Boot:accessDeniedHandler 不起作用

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM