如何在spring-security-javaconfig中添加Access Denied Handler

时间:2013-08-09 20:11:08

标签: java spring-security spring-java-config

我正在使用spring-security-javaconfig库来实现Spring安全性。如果我使用xml配置文件,我会使用类似这样的内容来定义自定义访问被拒绝页面:

<http auto-config="true">
    <intercept-url pattern="/admin*" access="ROLE_ADMIN" />
    <access-denied-handler ref="accessDeniedHandler"/>
</http>

到目前为止,这是我的安全配置类:

@Configuration
@EnableWebSecurity
public class SecurityConfigurator extends WebSecurityConfigurerAdapter {

    @Override
    protected void registerAuthentication(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
        auth.inMemoryAuthentication().withUser("admin").password("password").roles("ADMIN");

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeUrls().antMatchers( "/admin").hasRole("ADMIN");
    }
}

1 个答案:

答案 0 :(得分:30)

我想这应该可以解决问题:

HttpSecurity http = ...
http.exceptionHandling().accessDeniedHandler(myAccessDeniedHandler);