简体   繁体   English

自定义HTTP 403页面在Spring Security中不起作用

[英]Custom HTTP 403 page not working in Spring Security

I want to replace the default access denied page: 我想替换默认的拒绝访问页面:

HTTP 403

With my custom page and my approach was this: 使用我的自定义页面和我的方法是这样的:

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

    }   

}

But with this config above I'm still not getting the job done and seeing the same 但是通过上面这个配置,我仍然没有完成工作并且看到了相同的结果

HTTP 403

Are there more bean which must be injected for this purpose? 是否有更多的豆必须注入这个目的?

Disclaimer : this is not only solution, but a working one. 免责声明 :这不仅是解决方案,而且是一个有效的解决方案。

In this case my approach would be as simple as possible which is add this method in your SecurityContext 在这种情况下,我的方法将尽可能简单,即在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.
}

Reference: Custom 403 Page in Spring Security . 参考: Spring Security中的自定义403页面

As @M. 作为@M。 Deinum pointed out, you should tell Spring Security how to incorporate these beans. Deinum指出,您应该告诉Spring Security如何合并这些bean。 Anyway, there is a much simpler way for what you're trying to achieve: 无论如何,对于你想要实现的目标,有一种更简单的方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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