Java 自定义HTTP 403页在Spring安全中不起作用

Java 自定义HTTP 403页在Spring安全中不起作用,java,spring,spring-mvc,spring-security,Java,Spring,Spring Mvc,Spring Security,我要替换默认的拒绝访问页面: 对于我的自定义页面,我的方法是: @Configuration @EnableWebSecurity public class SecurityContextConfigurer extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override public void configure(WebSecuri

我要替换默认的拒绝访问页面:

对于我的自定义页面,我的方法是:

@Configuration
@EnableWebSecurity
public class SecurityContextConfigurer extends WebSecurityConfigurerAdapter {

    @Autowired
private UserDetailsService userDetailsService;

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/resources/**");
}

@Override
protected void configure(HttpSecurity http) throws Exception {

    http.sessionManagement().maximumSessions(1)
            .sessionRegistry(sessionRegistry()).expiredUrl("/");
    http.authorizeRequests().antMatchers("/").permitAll()
            .antMatchers("/register").permitAll()
            .antMatchers("/security/checkpoint/for/admin/**").hasRole("ADMIN")
            .antMatchers("/rest/users/**").hasRole("ADMIN").anyRequest()
            .authenticated().and().formLogin().loginPage("/")
            .defaultSuccessUrl("/welcome").permitAll().and().logout()
            .logoutUrl("/logout");
}

@Bean
public SessionRegistry sessionRegistry() {
    return new SessionRegistryImpl();
}

@Bean
public AuthenticationProvider daoAuthenticationProvider() {
    DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
    daoAuthenticationProvider.setUserDetailsService(userDetailsService);

    return daoAuthenticationProvider;

}

@Bean
public ProviderManager providerManager() {

    List<AuthenticationProvider> arg0 = new CopyOnWriteArrayList<AuthenticationProvider>();
    arg0.add(daoAuthenticationProvider());

    return  new ProviderManager(arg0);

}

@Bean(name = "myAuthenticationManagerBean")
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

@Override
protected AuthenticationManager authenticationManager() throws Exception {
    return providerManager();
}

    @Bean
    public ExceptionTranslationFilter exceptionTranslationFilter() {
        ExceptionTranslationFilter exceptionTranslationFilter = 
                new ExceptionTranslationFilter(new CustomAuthenticationEntryPoint());
        exceptionTranslationFilter.setAccessDeniedHandler(accessDeniedHandler());

        return exceptionTranslationFilter;
    }
    @Bean
    public AccessDeniedHandlerImpl accessDeniedHandler() {
        AccessDeniedHandlerImpl accessDeniedHandlerImpl = new 
                AccessDeniedHandlerImpl();
        accessDeniedHandlerImpl.setErrorPage("/page_403.jsp");
        System.out.println("ACCESS DENIED IS CALLED......");
        return accessDeniedHandlerImpl;
    }

    private class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint{

        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response,
                AuthenticationException authenticationException) throws IOException,
                ServletException {

            response.sendError(HttpServletResponse.SC_FORBIDDEN,
                    "Access denied.");
        }

    }   

}
@配置
@启用Web安全性
公共类SecurityContextConfigurer扩展了WebSecurity配置适配器{
@自动连线
私有用户详细信息服务用户详细信息服务;
@凌驾
public void configure(WebSecurity web)引发异常{
忽略().antMatchers(“/resources/**”);
}
@凌驾
受保护的无效配置(HttpSecurity http)引发异常{
http.sessionManagement().maximumSessions(1)
.sessionRegistry(sessionRegistry()).expiredUrl(“/”);
http.authorizeRequests().antMatchers(“/”).permitAll()
.antMatchers(“/register”).permitAll()
.antMatchers(“/security/checkpoint/for/admin/**”).hasRole(“admin”)
.antMatchers(“/rest/users/**”).hasRole(“ADMIN”).anyRequest()
.authenticated()和().formLogin().loginPage(“/”)
.defaultSuccessUrl(“/welcome”).permitAll()和()
.logoutUrl(“/logout”);
}
@豆子
公共会话注册表会话注册表(){
返回新的SessionRegistryImpl();
}
@豆子
公共AuthenticationProvider daoAuthenticationProvider(){
DAOAAuthenticationProvider DAOAAuthenticationProvider=新的DAOAAuthenticationProvider();
daoAuthenticationProvider.setUserDetailsService(userDetailsService);
返回daoAuthenticationProvider;
}
@豆子
公共ProviderManager ProviderManager(){
名单


是否有更多的bean需要为此注入?

正如@M.Deinum所指出的,您应该告诉Spring Security如何合并这些bean。无论如何,有一种更简单的方法可以实现您想要实现的目标:

@Configuration
@EnableWebSecurity
public class SecurityContextConfigurer extends WebSecurityConfigurerAdapter {
    // Rest omitted

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // The usual stuff
                .exceptionHandling()
                    .accessDeniedPage("/page_403.jsp")
                    .authenticationEntryPoint((request, response, authException) -> {
                        response.sendError(HttpServletResponse.SC_FORBIDDEN);
                    });
    }
}

免责声明:这不仅是一个解决方案,也是一个可行的解决方案

在这种情况下,我的方法将尽可能简单,即在SecurityContext中添加此方法

@Override
protected void configure(HttpSecurity http) throws Exception {

    http.sessionManagement().maximumSessions(1)
            .sessionRegistry(sessionRegistry()).expiredUrl("/");
    http.authorizeRequests().antMatchers("/").permitAll()
            .antMatchers("/register").permitAll()
            .antMatchers("/security/checkpoint/for/admin/**").hasRole("ADMIN")
            .antMatchers("/rest/users/**").hasRole("ADMIN").anyRequest()
            .authenticated().and().formLogin().loginPage("/")
            .defaultSuccessUrl("/welcome").permitAll().and().logout()
            .logoutUrl("/logout").and()
            .exceptionHandling().accessDeniedPage("/page_403");//this is what you have to do here to get job done.
}

参考:。

这更清楚地表明,除了几个bean之外,您没有配置任何东西。仅仅添加bean是没有帮助的,而且您正在使它变得复杂,这样做会更容易(请参阅答案和参考指南)。