2015-01-21 1156 views
7

我有以下春季安全配置:春季启动:accessDeniedHandler不起作用

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

我期待下面的逻辑:没有authenitcated用户会被重定向到/403。而不是Spring显示默认的Tomcat 403页面。我也尝试过自定义accessDeniedHandler,但没有取得任何成功。

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

回答

15

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

如果您想要更改该选项,则需要配置一个AuthenticationEntryPoint,当未经身份验证的用户尝试访问受保护资源时会调用该选项。你应该可以使用

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

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

1

正常的Spring Security行为是将未经身份验证的用户重定向到您的登录页面,如下配置。验证谁没有被授权的用户(不具有ADMIN角色)将被引导到拒绝访问页面:

http.authorizeRequests().antMatchers("/admin/**") 
    .access("hasRole('ADMIN')") 
    .and().formLogin().loginPage("/login") 
    .and().exceptionHandling().accessDeniedPage("/403"); 

如果实现自己的身份验证机制,你是不是在春季安全配置计数提供未经认证用户到您的登录页面,您可以按照以下方式游戏Spring Security配置 - 为您的自定义403页面而不是实际登录页面提供服务:

http.authorizeRequests().antMatchers("/admin/**") 
    .access("hasRole('ADMIN')") 
    .and().formLogin().loginPage("/403") 
    .and().exceptionHandling().accessDeniedPage("/403");